如果我理解正确,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)
我试图简单地将抛出函数作为参数传递给另一个函数,然后该函数将处理 swift 的错误处理:
enum Err: ErrorType {
case pfui
}
func bad(i: Int) throws -> String {
if i < 10 {
return String(i)
} else {
throw Err.pfui
}
}
func handle(@autoclosure f: () throws -> String) -> String {
do {
return try f()
}
catch {
return "oh snap"
}
}
// error: call can throw but is not marked with 'try'
handle(bad(3))
Run Code Online (Sandbox Code Playgroud)
它一定是我遗漏的一些简单的东西,但不知何故 autoclosure 属性并没有阻止编译器认为我实际上是在调用它。