抑制Swift中的隐式返回

前端之家收集整理的这篇文章主要介绍了抑制Swift中的隐式返回前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑以下一组功能
  1. func testFunc(someFunc: (Int[]) -> ()) {
  2. someFunc([1,2,3])
  3. }
  4.  
  5. func someFunc<T>(arr : T[]) -> T[] {
  6. return arr
  7. }
  8.  
  9. func someOtherFunc<T>(arr : T[]) {
  10. println(arr)
  11. }
  12.  
  13. // case 1 - ERROR
  14. testFunc() {
  15. someFunc($0)
  16. }
  17.  
  18. // case 2 - no error
  19. testFunc() {
  20. println("whatever")
  21. someFunc($0)
  22. }
  23.  
  24. // case 3 - no error
  25. testFunc() {
  26. someOtherFunc($0)
  27. }

看起来在情况1中,Swift试图从闭包中隐式返回,因为函数someFunc()返回一个值.只有在闭包中只有一行(单表达式闭包的隐式返回)时才会这样做 – 这就是案例2有效的原因.如果函数(如在情况3中为Void),即它不返回值,则不执行此操作.

我的问题是是否有一种方法可以抑制这种行为,这样我就可以在没有返回值的闭包中使用带有返回值的函数作为单行表达式.

除了提到的解决方案:
  1. testFunc { someFunc($0); return () } // returning Void explicitly (with or without parenthesis)
  2.  
  3. testFunc { someFunc($0); 42 } // or,indeed,just adding a second expression

您还可以使用返回的值:

  1. testFunc { let x = someFunc($0) }

或者干脆:

  1. testFunc { _ = someFunc($0) }

返回值必须始终是函数签名所承诺的类型,并且隐式返回的情况也不例外.这不是错误.简单地说,隐式返回通常是如此优雅的语法,不匹配类型的不太常见的情况是稍微破坏该咒语.这并不是说一个好的语法解决方案不会受欢迎,至少在预期Void的时候.也许就像这样简单:

  1. testFunc { someFunc($0) ; } // with the trailing semicolon

当这让我感到恼火时,最让我自己的功能迫使我围着它跳舞.我有几次使用显式忽略返回类型:

  1. func testFunc<Ignored>(someFunc: [Int] -> Ignored) {
  2. someFunc([1,3])
  3. }
  4.  
  5. testFunc { someFunc($0) }

猜你在找的Swift相关文章