Search code examples
swiftcastingswift5type-safety

Why Int and Float literals are allowed to be added, but Int and Float variables are not allowed to do the same in Swift?


I tried adding an Int and Float literal in Swift and it compiled without any error :

var sum = 4 + 5.0 // sum is assigned with value 9.0 and type Double

But, when I tried to do the same with Int and Float variables, I got a compile-time error and I had to type-cast any one operand to the other one's type for it to work:

var i: Int = 4
var f:Float = 5.0
var sum = i + f // Binary operator '+' cannot be applied to operands of type 'Int' and 'Float'

Why is it happening so ? Is it related to type safety in any way ?


Solution

  • In case of var sum = 4 + 5.0 the compiler automatically converts 4 to a float as that is what is required to perform the operation. Same happens if you write var x: Float = 4. The 4 is automatically converted to a float.

    In second case, since you have explicitly defined the type of the variable, the compiler does not have the freedom to change is as per the requirement.

    For solution, look at @Fabio 's answer