Swift 可以将 int 字面量推断为 double 或 float
let x: Float = 3
它甚至适用于算术。它会在计算之前转换所有内容,所以这也是 3:
let y: Float = 5/2 + 0.5
但这方面的实际规则是什么?存在不明确的情况,例如,如果推断是针对参数:
func foobar(_ x: Int) -> Int {
return x
}
func foobar(_ x: Float) -> Float {
return y
}
foobar(1/2)
在这种情况下,它会将其推断为 int 并返回 0,但如果您删除第一个函数,它会切换为 float 并返回 0.5。
规则是什么?它在哪里记录?
更烦人的是 Swift 可以将其推断为 float 但没有
func foobar(_ x: Float) -> Float {
return x
}
let x = 1/2
foobar(x) // Cannot convert value of type 'Int' to expected argument type 'Float'
最佳答案
文字没有这样的类型。文档说,
If there isn’t suitable type information available, Swift infers that the literal’s type is one of the default literal types defined in the Swift standard library. The default types are Int for integer literals, Double for floating-point literals, String for string literals, and Bool for Boolean literals.
因此,除非您的参数明确说明 Int
以外的任何内容,否则它将推断整数文字为 Int
。
更多信息请引用这里,Lexical Structure - Literals .
关于swift - Swift 的 int literal to float 推理是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52392373/