Search code examples
swiftif-statementmathematical-expressions

Correctly formulate if statement in switch


This might be a very rudimentary question, but I'm playing around with if statements and the following example won't work with error "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions". Does anybody know what I'm doing wrong?

let a = 4

let b = 3

let c = 10

let d = 2


if ((sqrt((a - b)^2 + (c - d)^2)) > 100) {
              print("Yes")
        }

Edit: I understood I made a few mistakes and now got it working with:

var a = 4

var b = 3

var c = 10

var d = 2

var e = (a-b)

var f = (c-d)

var g = (e*e)

var h = (f*f)

var j = Double(g+h)

if (j.squareRoot() > 5) {
              print("Yes")
      }

Solution

  • Use better types!

    import simd
    
    distance([4, 10] as SIMD2<Double>, [3, 2]) > 100
    

    And if you've really got to work with those integers…

    public extension SIMD where Scalar: FloatingPoint {
      init<Integer: BinaryInteger>(_ integers: Integer...) {
        self.init( integers.map(Scalar.init) )
      }
    }
    
    distance( SIMD2<Double>(a, c), .init(b, d) ) > 100