swift - Swift 的 int literal to float 推理是如何工作的?

标签 swift type-inference implicit-conversion

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/

相关文章:

string - Swift - 如何将连字符/减号转换为+号

c++ - 为什么这些重载函数调用不明确?

ios - Swift 类 init 抛出编译时错误 "expected declaration"

具有下限类型的 Java 类型推断

Scala 检查泛型类型

Typescript:如何从返回函数的输入参数推断高阶函数中的泛型类型

arrays - c 函数是否可以同时接受 double 和 long double 参数?

c# - 在隐式转换中使用字符串常量

ios - Swift 4 - 表达式太复杂,无法在合理的时间内快速解决

ios - UILabel 截断