考虑以下一组功能:
func testFunc(someFunc: (Int[]) -> ()) {
someFunc([1, 2, 3])
}
func someFunc<T>(arr : T[]) -> T[] {
return arr
}
func someOtherFunc<T>(arr : T[]) {
println(arr)
}
// case 1 - ERROR
testFunc() {
someFunc($0)
}
// case 2 - no error
testFunc() {
println("whatever")
someFunc($0)
}
// case 3 - no error
testFunc() {
someOtherFunc($0)
}
Run Code Online (Sandbox Code Playgroud)
看起来在情况1中,Swift试图从闭包中隐式返回,因为函数someFunc()返回一个值.只有在闭包中只有一行(单表达式闭包的隐式返回)时才会这样做 - 这就是案例2有效的原因.如果函数(如情况3所示)Void,即它不返回值,则不会执行此操作.
我的问题是是否有一种方法来抑制这种行为,以便我可以在没有返回值的闭包中将一个带有返回值的函数作为单行表达式.
除了提到的解决方案:
testFunc { someFunc($0); return () } // returning Void explicitly (with or without parenthesis)
testFunc { someFunc($0); 42 } // or, indeed, just adding a second expression
Run Code Online (Sandbox Code Playgroud)
您还可以使用返回的值:
testFunc { let x = someFunc($0) }
Run Code Online (Sandbox Code Playgroud)
或者干脆:
testFunc { _ = someFunc($0) }
Run Code Online (Sandbox Code Playgroud)
返回值必须始终是函数签名所承诺的类型,并且隐式返回的情况也不例外.这不是错误.简单地说,隐式返回通常是如此优雅的语法,以至于不匹配类型的不太常见的情况是稍微破坏该咒语.这并不是说一个好的语法解决方案不会受欢迎,至少在Void预期的时候.也许就像这样简单:
testFunc { someFunc($0) ; } // with the trailing semicolon
Run Code Online (Sandbox Code Playgroud)
当这让我感到烦恼时,最让我自己的功能迫使我围着它跳舞.我有几次使用显式忽略返回类型:
func testFunc<Ignored>(someFunc: [Int] -> Ignored) {
someFunc([1, 2, 3])
}
testFunc { someFunc($0) }
Run Code Online (Sandbox Code Playgroud)
更新:Swift 1.2 之后,这不再是问题
这个bug在Xcode beta6中仍然存在,我希望它能在1.0版本中修复,在此之前,这是一个解决方法
testFunc() {
someFunc($0)
// The explicit return statement corrects the wrong return type of the auto implicit return.
// It makes more sense than printing nonsense strings
return //TODO: remove after the bug is fixed
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3029 次 |
| 最近记录: |