简体   繁体   English

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

[英]Super simple trailing closure syntax in Swift

I am trying to follow the example in the Swift docs for a trailing closure. 我正在尝试遵循Swift文档中示例来进行结尾的闭包。

This is the function: 这是功能:

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

And I call it here. 我在这里称呼它。

        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

The function, however, is not getting called. 但是,该函数没有被调用。 What is wrong with the above? 上面有什么问题?

Here's the Apple example: 这是Apple的示例:

func someFunctionThatTakesAClosure(closure: () -> Void) { // function body goes here } func someFunctionThatTakesAClosure(closure:()-> Void){//函数体在这里}

// Here's how you call this function without using a trailing closure: //以下是不使用尾随闭包而调用此函数的方式:

someFunctionThatTakesAClosure(closure: { // closure's body goes here }) someFunctionThatTakesAClosure(closure:{//封闭体在这里})

Docs isn't very clear in explanation you need 文档对您所需的解释不是很清楚

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()
}  

the trailing closure is meant for completions like when you do a network request and finally return the response like this 尾随闭包用于完成操作,例如当您执行网络请求并最终返回响应时

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

And to call 并致电

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

what you missed to read 你错过了读什么

在此处输入图片说明

Here is your example fixed: 这是固定的示例:

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")

Output: 输出:

 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM