简体   繁体   中英

Super simple trailing closure syntax in Swift

I am trying to follow the example in the Swift docs for a trailing closure.

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:

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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