转换时是否需要显式区分大小写?

时间:2018-10-02 03:38:24

标签: swift

当我阅读swift文档时 https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html

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

这可行,但是,在以下情况下,如果我删除“双精度”,将无法正常工作。

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

请问为什么在第二种情况下我们需要显式转换类型?有什么区别?

1 个答案:

答案 0 :(得分:0)

这是因为Swift的自动类型推断。

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

而且由于无法将Double添加到Int,因此,您必须将三个包装为Double(three)

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

上面的代码起作用的原因是编译器发现两个求和输入都可以表示为Double,因此它将类型Double分配给 anotherPi 。希望这能消除您的疑问。