Tho*_*rer 5 generics types swift
如果我理解正确,Swift可以通过不同的方式确定泛型的实际类型,包括通过返回类型进行匹配.相同(或类似)机制用于消除重载函数的歧义.所以这按预期工作:
func getValue<T>()->T? {
return nil
}
func getValue()->Int? {
return 13
}
let b: Int? = getValue()
Run Code Online (Sandbox Code Playgroud)
运行时,b将是13.从技术上讲,两个函数签名都是合适的,但后者更适用于请求的返回类型.
让我们添加第二个函数并通过它来隧道调用:
func getGetValue<T>()->T? {
return getValue()
}
let c: Int? = getGetValue()
Run Code Online (Sandbox Code Playgroud)
运行时,c将是nil.实际上,编译器将选择从getGetValue()调用的泛型getValue()实现,这不是我想要的.恕我直言,在getValue()的两个实现之间进行选择时,请求的返回类型应该通过第二个泛型传播,从而产生与第一个示例中相同的行为.
我错过了什么?(Xcode 7.1)
你只是忘了施放。
func getValue<T>()->T? {
return nil
}
func getValue()->Int? {
return 13
}
let b: Int? = getValue() // 13
func getGetValue<T>()->T? {
return getValue() as? T
}
let c: Int? = getGetValue() // 13
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |