12.2 Trailing Closures
If you need to pass a closure expression to a function as the expression's final argument Swift also allows a alternate syntax called trailing closures. It is written after a function call's closing parenthesis ()
), even though it is still an argument to the function. When using this syntax, you don't need to write the argument label for the closure. For 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
})
// Here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
If we take our example function from the previous note, we can rewrite it using a trailing closure:
reversedNames = names.sorted() { $0 > $1 }
When a closure expression is provided as a function or method's only argument, and you provide it as a trailing closure, you do not need the parentheses (()
) after the function's name:
reversedNames = names.sorted { $0 > $1 }
Trailing closures are most useful in cases when the closure cannot be fit onto a single line.