What is trailing closure syntax in Swift?

前端 未结 4 1737
执笔经年
执笔经年 2020-12-06 23:12

Swift\'s documentation on closures states:

Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-fre

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 23:40

    If you need to pass a closure expression to a function as the function’s 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 call’s parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.

     func funcWithATrailingClosure(closure: () -> Void) {
    // function body goes here
     }
    
    // Here's how you call this function without using a trailing closure:
    funcWithATrailingClosure(closure: {
    // closure's body goes here
    })
    
    // Here's how you call this function with a trailing closure instead:
    funcWithATrailingClosure() {
    // trailing closure's body goes here
    }
    

提交回复
热议问题