Swfit trailing closure syntax

Trailing Closures

If you need to pass a closure expression to a function as the functions final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is written after the function calls parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you dont write the argument label for the closure as part of the function call.



  1. func someFunctionThatTakesAClosure(closure: () -> Void) {
  2. // function body goes here
  3. }
  4. // Here's how you call this function without using a trailing closure:
  5. someFunctionThatTakesAClosure(closure: {
  6. // closure's body goes here
  7. })
  8. // Here's how you call this function with a trailing closure instead:
  9. someFunctionThatTakesAClosure() {
  10. // trailing closure's body goes here
  11. }

评论

热门博文