Swift currently supports a special syntax for a single trailing closure which makes it possible to pass a closure as function's final argument after parentheses as a block without a label. This is very useful when the closure expression is long. I propose to extend this functionality to cover multiple closures instead of just one.
There has been some discussion about this previously at Pitch: Double (or more) trailing closures but since last September discussion has died down.
I'd like to pick it up and propose for new syntax we keep brace notation but allow the "body" enclosed in braces to have multiple labeled blocks, one for each trailing closure, that fits well into an existing model we have for calls as well as easy to implement in the parser.
In pseudocode it looks something like this:
<function, subscript, or contextual member> {
<label-1>: { ... }
<label-2>: { ... }
...
<label-N>: { ... }
}
Let's consider following function (slightly modified from original pitch):
func when<T>(_ condition: @autoclosure () -> Bool, then trueBranch: () -> T, `else` falseBranch: () -> T) -> T {
if condition() {
return trueBranch()
} else {
return falseBranch()
}
}
If new syntax gets adopted it would be possible to call it like this:
while (2 < 3) {
then: { 3 }
else: { 4 }
}
It also makes syntax more consistent and clean in combination with defaulted arguments e.g.
func transition(with view: View,
duration: TimeInterval,
animations: (() -> Void)? = nil,
completion: (() -> Void)? = nil) {
}
transition(with: view, duration: 2.0) {
print("which arg is this?")
}
It's not very clear just by looking at this code which argument is used because both of them are defaulted, so for readability it's much better to supply the label explicitly:
transition(with: view, duration: 2.0) {
completion: {
...
}
)
or
transition(with: view, duration: 2.0) {
animations: {
...
}
completion: {
...
}
)
I have an implementation for this new syntax available at [SE-0279][Parser] Add support for multiple trailing closures syntax by xedin · Pull Request #29745 · apple/swift · GitHub and going to post snapshots here once they become available.