1

when I read the doc of swift https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html

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

this works, however if I delete the "Double" in the following case, it does not work.

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine

May I ask why do we need to explicitly convert the type in second case? what is the difference?

FrankieWong
  • 53
  • 1
  • 7

1 Answers1

0

It is because of Swift's automatic type inference.

let three = 3 // Here **three** is inferred as Int 
let pointOneFourOneFiveNine = 0.14159  // Here **pointOneFourOneFiveNine** is inferred as Double 
let pi = Double(three) + pointOneFourOneFiveNine

And since you cannot add a Double to an Int, it’s the reason that you have to wrap the three as Double(three).

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

The reason the above code works because the compiler finds that both the summing inputs can be represented as Double, so it assigns the type Double to anotherPi. Hope this clears your doubt.

Aakash
  • 2,239
  • 15
  • 23