考虑以下一组功能:
- 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)
- }
看起来在情况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
您还可以使用返回的值:
- testFunc { let x = someFunc($0) }
或者干脆:
- testFunc { _ = someFunc($0) }
返回值必须始终是函数签名所承诺的类型,并且隐式返回的情况也不例外.这不是错误.简单地说,隐式返回通常是如此优雅的语法,不匹配类型的不太常见的情况是稍微破坏该咒语.这并不是说一个好的语法解决方案不会受欢迎,至少在预期Void的时候.也许就像这样简单:
- testFunc { someFunc($0) ; } // with the trailing semicolon
当这让我感到恼火时,最让我自己的功能迫使我围着它跳舞.我有几次使用显式忽略返回类型:
- func testFunc<Ignored>(someFunc: [Int] -> Ignored) {
- someFunc([1,3])
- }
- testFunc { someFunc($0) }