使用来自 Swift Language Guide: Extensions 的示例代码我已经像这样扩展了 struct Double
extension Double {
func someFunc() {
print("someFunc")
}
}
我很惊讶这个说法
2.someFunc()
没有生成编译时错误,例如:“Int”类型的值没有成员“someFunc”。我期望 2 的值被隐式转换为 Int,但 Swift 将其转换为 Double。这是为什么 ?在这种情况下,Swift 如何确定 2 的值是 Double 类型?
然后我尝试像那样调用 someFunc()
let x = 2
x.someFunc()
这里我得到了预期的编译时错误
这与 Swift Programming Language 3.0.1 : Language guide : The basics : Type Safety and Type Inference 中的陈述是否矛盾? ?
Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide.
编辑
从回复中我了解到它的发生是因为 Double 符合 ExpressibleByIntegerLiteral 协议(protocol)。但是 Float 结构也确实符合它和其他一些类型。下面我创建了也符合该协议(protocol)的结构。但是最后在编译时选择了 Double。为什么?如何确定一个扩展的方法相对于其他扩展的方法的优先级?
struct someStruct: ExpressibleByIntegerLiteral{
var i:Int = 0
init(integerLiteral value: Int64){
i = Int(value)
}
}
extension someStruct {
func someFunc() {print("Somestruct someFunc") }
}
extension Double {
func someFunc() { print("Double someFunc") }
}
4.someFunc()
//prints: Double someFunc
最佳答案
Double是符合协议(protocol)ExpressibleByIntegerLiteral的类型之一.由于 2 是一个整数字母,编译器可以检查哪些符合协议(protocol)的类型有 someFunc() 并且因为只有 Double 有,所以在这个上下文中没有歧义。
关于swift - Swift 中的隐式类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41012504/