SE-0279: Multiple Trailing Closures [Amended]

IMO that would only be true if there was no duration parameter. Since there is, it interrupts any natural association between the closure and the leading verb, so I don't think it provides the context you think it does. Additionally, the content of the closure in the drop { } case can help hint towards what it means since it returns a Bool, while the animate block is just a list of property mutations, with nothing that indicates an animation. Additionally, I don't like the animate example at all, since that's not likely how the method would be written if it were Swift native.

How would you write it?

Let me use UIView.animate as an example for code completion behavior:


SourceKit suggests both

  • animate(withDuration: TimeInterval, animation: () -> Void, completion: (() -> Void)?)
  • animate(withDuration: TimeInterval, animation: () -> Void)

as before.

If you select the former one, the code becomes

When you hit enter key at the animations placeholder, SourceKit automatically checks if the rest of the arguments can be trailing closures, and if yes, it turns this whole expression to:

If you select the latter one, since there's only one possible trailing closure argument, the placeholder expansion is exact the same as before

But, if you want to add completion argument after that, SourceKit is able to suggest it after the closing brace of the first closure.

This additional trailing closure completion should work even at the newline position

But in this case, global symbols are also suggested because you might be adding another statement.


Why this special treatment for the first closure, e.g. no label there? Only to make things like:

when(2 < 3) {
} else: {

possible? This looks very much like a tailor-made solution for a very special case. I wouldn't mind:

when(2 < 3) then: {
} else: {

e.g. having labels for all closures, which appears much more sane to me.





The proposed syntax removes a significant pain point when designing and using APIs that take multiple closures. The resulting syntax at point of use is pleasant, clear, and concise. This should be particular true for APIs designed with the new calling syntax in mind. The new API design guidelines around base names are welcome.

I also really appreciate that the proposed syntax and API design guidelines result in calling code that is easy to evolve by adding additional parameters.

The proposal does put some additional burden on API designers to develop an appropriate set of method overloads, especially given the necessary constraints on matching arguments to defaulted parameters. That burden strikes me as a reasonable price to pay for the improved clarity at point of use.

Yes. It’s always been awkward in Swift to call methods taking multiple closures. Existing single-closure methods are also sometimes awkward with a trailing closure; drop { … } being the canonical example. Frameworks like Combine and SwiftUI lean heavily on closures, so the existing pain points have become more acute.

I think so. It’s a comfortable extension of the existing trailing closure syntax that also smooths over some rough edges.

I’ve used C APIs that take multiple function pointers, ObjC APIs that take multiple blocks, and Swift APIs that take multiple closures. The proposed syntax is an improvement on all of them.

I read the entirety of the initial review thread (really!), studied the revised proposal in depth, and experimented with a variety of alternative spellings for passing multiple closures. Of the alternatives I’ve seen, the proposed syntax, when paired with API design that takes advantage of it, offers the best combination of clarity at point of use plus simplicity when evolving calling code.

1 Like

I read the proposal and also the Renaming Trailing-closure Functions in the Standard Library. But I will try not to off-topic here.

It’s kind of unfortunate the first labeled closure is omitted in the proposal.

As someone has already mentioned above that the label of the first closure is important in certain APIs and I’m doubted whether it’s possible to remove them all and put into function names.

I prefer first where: { ... } over firstWhere: { ... }.

And also the example Bind(get:set:) from @Lantua. How would you rename it if the first label is omitted? Abstract that by protocols seems too heavy to me.

But in some cases, omitting the first label is good and don’t harm readability.

Even from the teaching/learning perspective, I believe no special case is always a better choice. We have to learn how to use multiple closures anyway if the proposal is accepted. No matter how many closures a function takes, one or many, the first or the remaining, all follow the same rules.

To summarize my points, I think I would prefer a more balanced solution for the first labeled closure.


Another example from SwiftUI where the omission of the first trailing closure label feels strange:

Binding { 
} set: { newValue in
  self.value = newValue 

Ideally I'd prefer to use the first closure label explicitly:

  get: { 
  set: { newValue in
    self.value = newValue 

@Lantua already mentioned this briefly above.


Having put more time in reading the points in favor of requiring a label also for the first closure, I can say that now I 100% agree with those, for a variety of reasons. The first, and most important, is that it doesn't make any sense to treat the first closure as "special", even if this is the current Swift behavior (in the sense that the current trailing closure syntax omits the argument label). For a lot of APIs, both existing and potential, skipping the the label for the first closure would make the code harder to understand at call site, there's no getting around it.

The only special rule I'd suggest, to make things like the when example possible, is the possibility to omit the first argument when it's _:.


The proposed syntax is a step forward as compared to the previous iteration.

I do appreciate the effort that has gone into making truly multiple trailing closure expressions a reality--for instance, making it easier on the parser when it comes to default:.

I understand the motivation that some closures seem more important than others in a function call and therefore providing some way to elide one argument label. It is certainly elegant in that favorite toy example of ours, when(then:else:).

However, as the review feedback has shown, it is quite possible to provide many examples where there are multiple equally important closure arguments. I would therefore caution against overfitting to APIs we already have, since those have been designed explicitly for a language where only a single trailing closure syntax is available.

Moreover, we have seen examples where it might be optimal to label the closure even when there's only one argument. This is not only for cases where the label might provide call-site clarity. @allevato makes an excellent point that a labeled trailing closure syntax would solve the issue where existing trailing closure syntax can't be used in the condition of an if statement without parentheses:

My principal concern, however, regarding first-closure label elision is the "backward scan" rule.

By construction, if there are multiple closures, and one label may (or, in this version of the proposal, must) be elided, then there must be some rule to figure out which argument corresponds to the unlabeled closure. This is not just a difficulty for the machine, but also for the human reader.

I appreciate that much effort has been made so that it's more predictable or consistent which argument is unlabeled if an additional closure argument is added, or if it is of optional type, or if a default value is added. The degree of explanation required, however, for the reader to determine which argument is the unlabeled closure is mindblowing, as reflected in the length of text devoted to that purpose in the proposal. And if it is to be redone for Swift 6, all the more so.

Certainly, the backward scan rule is not teachable even if one might argue that it is the most usable possible rule. However, I am skeptical than any rule for matching unlabeled closures to arguments, even if optimally redone for Swift 6 in a source-breaking way, would be more usable than not having to have a rule at all (that is, by requiring all labels).

I do not think that the requirement for a language rule, whether "backward scan" or the possible source-breaking future "forward scan," is an adequate tradeoff to avoid repeating the word "animate" at the call site.

For that reason, and for the reasons above, I agree with @jrose that the rule should be (as was proposed in the first review): if you have multiple closures, all must take an argument label; if you have exactly one trailing closure, the argument label may be omitted.

The ability to omit the label for a single trailing closure expression goes some way (in the vein of the 80% rule) to ameliorating the use case where one closure is more important than the rest (limited, obviously, to cases where "the rest" have default values or are optional).

The core team having already decided that the underlying motivation for the proposal does merit a change, I will consider this question to be out of scope for this re-review.

See above.

I have used the trailing closure syntax already present in this language. I made the suggestion during the first review that was the basis for this revised syntax, so I'd say I have some familiarity with the topic (speaking of, some acknowledgment might be nice?). I have read the diff and followed along with the implementation.


(My apologies if this has been discussed before, as I didn't have the time to read the full thread)

I worry that this proposal adds additional complexity to an already overcomplicated feature. Please keep in mind that trailing closures are optional, in that a user is never required to use them, yet library designers often design their APIs with trailing closures in mind. However, for many newcomers, trailing closures are a confusing and alien-looking feature. I've seen many students avoid them for months, because they find it easier to learn the language using regular closure arguments, which are more consistent with the rest of the language.

Is it not possible to resolve this "first parameter" discussion by removing complexity from the language, instead of adding it? If the Standard Library is open for changes, can we not simply remove the exception that a trailing closure argument drops its argument label, and return to a state of symmetry where it's up to a library author to decide whether an argument requires a label or not, and that this label is required, both for a regular closure argument, and for a trailing closure?


What do you think of the slight variant suggested by @xwu and @jrose below (amended by me for clarity)? It also simplifies the rules, and would break less existing code:

I just made a run through Xcode doc. The first thing I observed is that multiple-closure is rare, which is expected of pre-SE-0279 era. Nonetheless, I found a few of them. The proposal already mentioned animate function, and Section init. I wanted to add that, currently, there aren't a lot of other functions outside of that. Anyhow, they all generally fall into these categories:

Action & Completion

They are functions of the form:

func doSomething(thatSomething: (Param) -> (), completionHandler: (Result) -> ())
Boring list

There's also a large subset where action is the animation blocks, which can be found in pretty much any animation-related functions in
UIView, UIViewController, UIViewPropertyAnimator, UIViewControllerTransitionCoordinator, UIFocusAnimationCoordinator, UIGraphicsRenderer. An example includes the discussed animate(withDuration:animations:completion:).

This would match @John_McCall's conjecture earlier that functions would have one main closure (action) and a few lesser closures. Note still that some functions in these category have defaulted (action) closures, so it doesn't fit the mould perfectly.

Event Handlers

They are functions that sets a few event handlers together. Most notably in Combine's Publisher functions:

Boring list

These functions fit more to @jrose's concern where none of the closures are mandatory (breakpoint, handleEvents), or all of them are (sink).

Notably, there're also a lot of functions that use one completion handler like so:

doSomething(..., completionHandler: (Succeed?, Error?) -> ())

Arguably this could be split into succeed closure and error closure, but it could also use Result type, or even async-await.


These are mostly SwiftUI functions, that has one main View closure, and a few accompanying closures. Some also have another View closure for nested contents.

Boring List


There are two functions I found so far that don't really fit into any category

So I'm inclined to agree that this is more of an exception rather than the norm.

From what I see, an overwhelming majority are animate & completion functions. All other categories become so rare that I did just listed all functions that I found. One caveat is that the API frequency doesn't translate to usage frequency.

Edit: Just added some more... Don't mind me :stuck_out_tongue:


Thanks for taking the time to compile this!


There's one thing I'm concerned with, is that the omitted label is now decided by the caller, not the author. It's actually not obvious that the callers will always start with the first available closure. The callers can do any of these

doSomething {
  // Do that something
} onComplete {
  // Complete
} onFailure {
  // Failure

doSomething(self.preset) {
  // Complete
} onFailure {
  // Failure

doSomething(self.preset, onComplete: self.genericUpdate) {
  // Failure

And I don't think we'd outright reject the latter two. They look like something the proposal would accept, and it can be hard for human to read.


Quick Answers

I like the general direction this proposal is going towards, but I'm hesitant on the details.

It is a long lasting problem that generates a large interest in fixing it among the community. However, I don't think the current proposal is good enough yet for a change to Swift.

Largely, yes, but not completely.


I did not participate in the review of the previous version. I read the revised proposal in full. I'm participating in the discussion of Renaming Trailing-closure Functions in the Standard Library

Detailed Review

First, questions: How would this deal with parameter ordering? Would it be ok if the trailing closures are rearranged, so long as the labels are correctly paired with the closures? What happens when there are labels by the same name?

Now, some disagreements:

If labelling the first trailing closure were allowed, users would have to evaluate whether to include the label on a case by case basis, which would inevitably lead to linter and style guide rules to prohibit it.

I'm not sold on this argument. Potential future linter and style guide rules shouldn't matter this much to the language itself. Swift allows optional semicolons, and there must be some projects somewhere that mandate semicolon at the end of every statement, but this doesn't mean Swift should enforce no semicolons when statements are on their own lines. Similarly, Swift is indifferent to indentation styles, but different linter and style guides' rules on "spaces vs. tabs" and brace-placements don't matter to the language itself.

Recall: API authors should be naming functions assuming that the argument label of the first trailing closure will be dropped. Swift users aren’t used to seeing function names and argument labels juxtaposed without parenthesis. Many find this spelling unsettling.

I'm not sold on this argument, either. The first part is based on the proposed change to the API design guide. The second part is contradictory to the nature of Swift Evolution itself. Many things in Swift today were not familiar to users before, this proposal included if accepted. Further, what's unsettling should be determined by new users' reaction, not existing users'. In contradiction to the proposal authors' argument, I believe consistency in spelling among trailing closures is more comfortable for both new and existing users. If some of them happen to find it unsettling to have a label for the first trailing closure, they have the option of dropping it.

> The existing trailing-closure feature requires special treatment of the trailing-closure argument by the type checker because of the special power of label omission: the trailing closure can be passed to a parameter that would ordinarily require an argument label. Currently, the special treatment is specific to the final argument. Because this proposal still has an unlabeled trailing-closure argument, we have to generalize that treatment to allow label omission at an intermediate argument.

Why not just get rid of the special treatment entirely? I prefer @michelf's solution. It's elegant and backward compatible.

In general, the forced omission of the first trailing closure label is practically reintroducing a problem that SE-0046 fixed in a slightly different context.

A Possible Digression

Can this proposal be extended to function declarations as well? For a default parameter value that's a large block of code, it should be very helpful to allow it to be trailing.

I should add to my previous post that the same point here applies the other way. If all labels are required off the bat and lived experience shows that eliding the first (or last) label is really valuable, that will also be a straightforward future extension. Moreover, if it can allows us to avoid the "backward scan rule now, but potentially a different source-breaking rule in Swift 6" situation, then that would be all the more preferable.


Note that there's already a backward scan rule for the single-trailing-closure case.

Right, hence the source-breaking part if it's to be changed. The proposal makes it clear that the issue of which argument is referred to by an unlabeled trailing closure is made greatly more challenging when multiple closures can be trailing, and the existing rule is clearly not what we would choose in that circumstance given a blank slate.

Could you elaborate on this point? Michel's proposal is to allow functions to opt in to requiring the use of a label on a trailing closure (and assumes that this proposal is modified to allow all trailing closures to be labeled). It doesn't change the special treatment of unlabeled trailing closures; changing that would not be backward-compatible, as would be adopting Michel's annotation on any existing functions.