Kris2k
Kris2k

Reputation: 367

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 ?

Upvotes: 0

Views: 601

Answers (3)

Suyash Medhavi
Suyash Medhavi

Reputation: 1238

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

Upvotes: 1

delibalta
delibalta

Reputation: 298

The document on Swift.org says:

Type inference is particularly useful when you declare a constant or variable with an initial value. This is often done by assigning a literal value (or literal) to the constant or variable at the point that you declare it. (A literal value is a value that appears directly in your source code, such as 42 and 3.14159 in the examples below.)

For example, if you assign a literal value of 42 to a new constant without saying what type it is, Swift infers that you want the constant to be an Int, because you have initialized it with a number that looks like an integer:

let meaningOfLife = 42 // meaningOfLife is inferred to be of type Int

Likewise, if you don’t specify a type for a floating-point literal, Swift infers that you want to create a Double:

let pi = 3.14159 // pi is inferred to be of type Double Swift always

chooses Double (rather than Float) when inferring the type of floating-point numbers.

If you combine integer and floating-point literals in an expression, a type of Double will be inferred from the context:

> let anotherPi = 3 + 0.14159 // anotherPi is also inferred to be of

type Double The literal value of 3 has no explicit type in and of itself, and so an appropriate output type of Double is inferred from the presence of a floating-point literal as part of the addition.

Upvotes: 1

Fabio
Fabio

Reputation: 5628

If you want Double result:

let i: Int = 4
let f: Float = 5.0
let sum = Double(i) + Double(f)
print("This is the sum:", sum)

If you want Int result:

let i: Int = 4
let f: Float = 5.0
let sum = i + Int(f)
print("This is the sum:", sum)

Upvotes: 2

Related Questions