MikeJfromVA
MikeJfromVA

Reputation: 513

How are Swift array types treated differently from assignment to operator?

Is there a different policy for type inference when assigning variables vs. binary operator?

let arrayOfInts = [1,2,3]
let arrayOfDoubles = [1.0, 2.0, 3.0]
// arrayOfInts == arrayOfDoubles 
// Binary operator '==' cannot be applied to ... [Int] [Double]
[1,2,3] == [1.0, 2.0, 3.0] // works?

Upvotes: 2

Views: 31

Answers (1)

Hamish
Hamish

Reputation: 80941

With arrayOfInts, the compiler by default infers the integer literals to be of type Int. Thus arrayOfInts is an [Int]. With arrayOfDoubles, the compiler will by default infer the floating point literals to be of type Double. Thus arrayOfDoubles is of type [Double]. You cannot compare a [Int] with a [Double] (at least not with the standard library's overloads of ==), therefore you'll get a compiler error.

However, with the expression [1, 2, 3] == [1.0, 2.0, 3.0] – Swift can infer both the floating point and integer literals to be of type Double, as Double conforms to both ExpressibleByIntegerLiteral and ExpressibleByFloatLiteral. Therefore you're comparing a [Double] with a [Double] – which is legal.

Upvotes: 3

Related Questions