Extend the example in “The Swift Programming Language” (Swift 5.5) “Integer and Floating-Point Conversion”:
3 0.14 // allowed
let three = 3
let rest = 0.14
3 rest // allowed
0.14 three // compile error
three 0.14 // compile error
I don’t understand why the last two lines are taken as compile error. Can anyone help to explain a bit? Thanks.
CodePudding user response:
There are two basic rules:
- A numeric literal without type annotation can be converted implicitly if possible.
- A constant or variable is initialized with a fixed type which cannot change. A floating point literal becomes
Double
and an integer literal becomesInt
.
So three
is Int
and 0.14
is Double
.
3 rest
works because 3
can be inferred as Double.
But 0.14
cannot be inferred as Int
so the last two lines fail to compile.