Swift 中超级简单的尾随闭包语法

Super simple trailing closure syntax in Swift

我正在尝试跟随 example in the Swift docs 进行尾随闭包。

这是函数:

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
    print("we do something here and then go back")//does not print
}

我在这里称呼它。

        print("about to call function")//prints ok
        someFunctionThatTakesAClosure(closure: {
            print("we did what was in the function and can now do something else")//does not print
        })
        print("after calling function")//prints ok

但是,函数没有被调用。以上有什么问题吗?

这是 Apple 示例:

func someFunctionThatTakesAClosure(closure: () -> Void) { // function body goes here }

// Here's how you call this function without using a trailing closure:

someFunctionThatTakesAClosure(closure: { // closure's body goes here })

文档对您需要的解释不是很清楚

print("1")
someFunctionThatTakesAClosure() {  // can be also  someFunctionThatTakesAClosure { without ()
    print("3") 

}

func someFunctionThatTakesAClosure(closure: () -> Void) { 
   print("2") 

   /// do you job here and line blow will get you back
    closure()
}  

尾随闭包用于完成,例如当您执行网络请求时,最后 return 像这样的响应

func someFunctionThatTakesAClosure(completion:  @escaping ([String]) -> Void) { 
   print("inside the function body") 
   Api.getData { 
      completion(arr)
   }
}  

并打电话给

print("Before calling the function")
someFunctionThatTakesAClosure { (arr) in
  print("Inside the function callback  / trailing closure " , arr)
}
print("After calling the function") 

你错过了什么

这是您修复的示例:

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
    print("we do something here and then go back")

    // don't forget to call the closure
    closure()
}


print("about to call function")

// call the function using trailing closure syntax
someFunctionThatTakesAClosure() {
    print("we did what was in the function and can now do something else")
}

print("after calling function")

输出:

about to call function
we do something here and then go back
we did what was in the function and can now do something else
after calling function