What is trailing closure syntax in Swift?

前端 未结 4 1656
执笔经年
执笔经年 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:48

    Trailing Closures

    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.

    https://docs.swift.org/swift-book/LanguageGuide/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID102

    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
    })
    
    // Here's how you call this function with a trailing closure instead:
    
    someFunctionThatTakesAClosure() {
        // trailing closure's body goes here
    }
    

    If a closure expression is provided as the function or method’s only argument and you provide that expression as a trailing closure, you do not need to write a pair of parentheses () after the function or method’s name when you call the function:

    reversedNames = names.sorted { $0 > $1 }
    

提交回复
热议问题