When you add an integer constant to a Double, the resultant type would also be a Double type.
When you add an integer constant to a Float , the resultant type would also be a Float type.
var sum1 = 5 + num1 //num1 and sum1 are both Double var sum2 = 5 + num2 //num2 and sum2 are both Float
However, if you try to add Int and Double variables, you will get an error:
var i4: Int = 123 var f1: Double = 3.14567 var r = i4 + f1 //error
To add two variables of different types, you need to cast the Int variable to Double :
var r = Double (i4) + f1
When adding an integer to a floating-point number, the result would be a Double value. For example:
var someNumber = 5 + 3.14
Here, someNumber would be inferred to be a Double.
In Swift, there is no implicit type conversion-you must explicitly convert an to a Float or Double:
var f:Float var i:Int = 5 f = i //error f = Float (i)
When casting a floating-point value to an integer, the value is always truncated:you will lose its fractional part:
var floatNum = 3.5 var intNum = Int(floatNum) //intNum is now 3