Devil Decoder
Devil Decoder

Reputation: 1086

Need help on type inference in swift

when i was reading about type inference in swift i came to know that swift is smart enough to know about data types

like when i write this program

var v3 = 2+2.5
print("the result is \(v3)")

then i see output

the result is 4.5

but when i write this program

var v1 = 2.5
var v2 = 2
var v3:Double = v1 + v2
print("the result is \(v3)")

then it gives me this error

ERROR at line 7, col 20: binary operator '+' cannot be applied to operands of type 'Double' and 'Int'
var v3:Double = v1 + v2
                ~~ ^ ~~
NOTE at line 7, col 20: expected an argument list of type '(Double, Double)'
var v3:Double = v1 + v2

so can anyone explain me what is going on here

i have done this program on IBM sandbox

Upvotes: 0

Views: 196

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

When you write var v3 = 2+2.5 Swift has to infer the type of 2, a numeric literal compatible both with Int and Double. The compiler is able to do so, because there's 2.5 in the same expression, which is a Double. Hence, the compiler concludes that 2 must also be a Double. The compiler computes the sum, and sets v3 to 4.5. No addition is performed at runtime.

When you write var v2 = 2 the compiler treats 2 as an Int, making v1 and Int as well. Now there is an addition on the var v3:Double = v1 + v2, which fails because v1 and v2 have mismatched types.

If you declare var v2:Double = 2 instead, the problem will be fixed.

Upvotes: 3

Related Questions