SE-0279: Multiple Trailing Closures [Amended]

You're right. But this situation is far from ideal for proposals of this kind. Some people here may end up fostering their future pet-peeve, without any recourse. This is a problem.

I hope the core team will bring back the subject of formatting on the table very soon and very seriously, even though the end result may turn out as brutal as the transition to Swift 3, and that such proposals have to contain a formatting section, and an implementation for the formatter as well.

End of the "meta" topic, sorry for the interruption.

1 Like

Moderation note

While I agree, this is really a separate discussion from the review, so I've started a thread to discuss this particular issue. Please discuss the potential changes to the standard library there.

It's a fine line, because discussion of the rules for multiple trailing closures is perhaps helped by considering the current challenges of labels with trailing closures. But specifically addressing what exists in the standard library should go in the other thread.


I tried to play around with some extensions that I'm currently using, and how they could change if this is implemented.

extension Optional {
  func forEach(_ body: (Wrapped) throws -> Void, ifNone: () throws -> Void = {}) rethrows {
    if let self = self {
      try body(self)
    } else {
      try ifNone()

let x1: Int? = 42

/// This is great
x1.forEach {
} ifNone: {

extension Collection {
  func forEach(_ body: (Element) throws -> Void, ifEmpty: () throws -> Void = {}) rethrows {
    guard !isEmpty else {
      try ifEmpty()

    for element in self {
      try body(element)

let x2 = [1, 2, 3]

/// This is amazing, but using `forEach` would require a change in the standard library
x2.forEach {
} ifEmpty: {

extension Result {
  func fold<A>(onSuccess: (Success) -> A, onFailure: (Failure) -> A) -> A {
    switch self {
    case let .success(value):
      return onSuccess(value)

    case let .failure(error):
      return onFailure(error)

let x3 = Result<Int, Error>.success(42)

/// This is ugly, it's not clear without the first label
let x4 = x3.fold {
  $0 * 2
} onFailure: { _ in

/// This is better, and it's the current syntax.
/// It should be preferred when the method name is too generic sounding, and argument labels give the appropriate meanings to the closures.
let x5 = x3.fold(
  onSuccess: { $0 * 2},
  onFailure: { _ in 0 }

Overall, this seems excellent. I'd probably review some current APIs to better accomodate this proposal, as already mentioned, but it's a separate discussion. The glorious when example should be, for me, an instant addition to the standard library.

I think this is definitely in line with the direction of Swift, and the additional convenience seems to warrant this change.

I could imagine myself to prefer this form if it was allowed.

    onSuccess: { $0 * 2 }
    onFailure: { _ in 0 }
  .distance(to: 42)

This is a good example where the closures really are peers. Not supporting a label for the first closure in this case would be actively harmful.

If we need to support it in some cases then change to the API Design Guidelines be revised:

Name functions assuming that trailing closure syntax will be used. Include meaningful argument labels for closures when their meaning is not clear from the base name alone.

If we go in this direction, maybe we should consider deprecating trailing closure label elision altogether. This is a much larger change to the language, but would align declaration with usage and ensure all call sites are consistent.

The misalignment of declaration and usage could be considered actively harmful in the presence of an alternative that makes the language more consistent. For example, usage sites such as array.first { ... } require the reader to know more about first than should be required.

I'm not sure what migration might look like, but perhaps static analysis could infer whether a label should be required or not from usage sites.


I haven't done a deep review, but I agree with Jordan and others who say that we shouldn't provide special behavior to the first closure parameter just because it was first. All closure should have to respect the labels provided by the API author.

Now, the proposal provides parsing and grammar rules for the compiler to be able to parse peculiar expressions of this logic, but that doesn't help users at all, especially when the parameters are unlabeled or defaulted.

func pointFromClosures(x: () -> Int = { 0 },
                       _ y: () -> Int = { 0 },
                       _ z: () -> Int = { 0 }) -> (Int, Int, Int) {
    (x(), y(), z())

Now what does this mean:

pointFromClosures { 1 }

If you're familiar with the peculiar rules of this new multiple closure behavior, you'd know that it's x getting the value there. However, if you have any previous Swift experience, you might assume it's z, as the trailing closure, that gets the value. I think this is a problem: this new syntax is incompatible with current Swift behavior while appearing the same.

Another problem:

    _: { 2 }

Which closure gets the value 2, y or z? If you following the parsing rules laid out in the proposal you'd know it was y, but most users won't know that. So with these new complex rules, there's little the user can do to intuit a correct result.

And a final issue:

pointFromClosures {
} _: {
} _: {

This just looks bad. I think full excision of labels looks better.

{ 1 } 
{ 2 }
{ 3 }

Ultimately, though, much of the issue here was just bad API design, so lets assume we fully labeled the closures:

{ 1 } 
y: { 2 }
z: { 3 }

Like @anandabits said, this looks odd as well, since the values are peers and should have the same labeling requirements.

Finally, I take issue with this text in the "Alternatives Proposed" section:

While this syntax is clear at the point of use, pleasant to read, and provides contextual cues by separating the trailing closures from the rest of the arguments, it risks evolving into an alternative calling syntax. The proposed syntax is more concise and less nested, without loss of clarity:

UIView.animate(withDuration: 0.3) {
  self.view.alpha = 0
} completion: { _ in

We have a new topic talking about this precise issue, so I don't think you can argue there's no loss of clarity: you'd have to understand what the first closure does in the animate example just like in the count example from the other topic. It's been brought up earlier in this topic, but I found the responses to be less than satisfying.

Overall, I'm not sure this proposal goes far enough to distinguish between closures of relative importance, fully solves the usability issues around multiple trailing closures for typical users, or gives API developers the tools necessary to guide such users toward the intended call sites.


It is in fact z that gets the value, and then the call doesn't type-check. Also it's impossible to change this without a source change because this is currently-supported syntax. The proposal does go into this.

This isn't legal under the proposal.

Ah. I think this makes it worse then, as it would provide two completely different unlabeled trailing closure rules.

Which part? Multiple unlabeled closures?


You’re literally pointing at the current Swift behavior and saying “this makes it worse”. I think you’ve just misunderstood the proposal.

Labelling the first trailing closure in a call.

I realized this doesn’t quite capture what I intended. I didn’t mean to imply that the _: “placeholder” label would be required for the first trailing closure argument.


Ah yes, I see. I wouldn't be able to use the trailing syntax to set just the y or z (or y and z) closures, in that case, would I?

Correct, the proposed syntax does not allow you to be explicit about which parameter you're intending to supply, in cases where they're all defaulted. This API, if it existed, would match poorly with this proposal.

-1. More complexity and more special syntax is a bad thing in my opinion. Swift seem to be ever-expanding into having more and more stuff in the language.

No, it's just more syntax and options in an already very complex language.

Personally, I wish swift would have gone the opposite route: making trailing closures an opt-in feature for functions, so that only functions for which it makes sense (e.g. DispatchQueue. and friends) could this special syntax.

No comment. It's hard to say what the feel and direction of Swift actually is with so many moving parts.


Followed all the threads.


No, I'm saying the more I learn about the complexities this proposal brings to the considerations users have to make around trailing closures, the "worse" I think of it. Swift will now have the following rules, if I'm understanding correctly:

  • Single closure at the end of a function, you can:
    • Use it labeled.
    • Use it with trailing syntax.
  • Multiple closures, all at the end of the function, you can:
    • Use them all labeled.
    • Use all but the last labeled, use the last with trailing closure syntax.
  • Multiple closures, all at the end of the function, with the new syntax, you can:
    • Use them all labeled.
    • Use all but the last labeled, use the last with trailing closure syntax.
    • Use the first as a trailing closure.
      • If the rest of the closures are defaulted, it looks like typical trailing closure usage.
      • If any are not defaulted, you must use the trailing syntax first, then add labels for the additional closures.
      • If multiple defaulted closures are unlabeled you can't disambiguate between them and so can't use the trailing syntax at all. Though this is also true when using them inline (I think), and so may be a bad example.

I really think it would simplify the user's consideration here to make the first closure elision contingent on not having an external label. That way API designers could have some control over this form and not have to move things around for the multiple closure case. Take this (fake) API for something like Alamofire (types elided).

func request(..., modifier: {}, uploadProgress: {}, downloadProgress: {}, completion: {})

In this function, completion is the most important, and likely the only one not defaulted. However, in trying to use this function with the trailing syntax I'd be forced to either create an alternate form where completion is first, which is rather illogical, or use requestModifier as a trailing closure:

request(...) {
    $0.timeoutInterval = 5
} completion: {

Instead, it seems like, by having an external label on the parameter, I'm saying that users should label it, if it's used. We do lose any name elision in that case, but I think that's okay.

    requestModifier: {
        $0.timeoutInterval = 5
    } completion: {

I'm also extremely interested in how the tooling, especially Xcode, will handle the autocomplete here. How will users activate the multiple trailing closure syntax with autocomplete versus inline labels or trailing closure syntax? I'd hate yet another Xcode hack to only enable this for certain APIs, like SwiftUI. It also seems like we'll need some sort of autocomplete when the user is typing multiple trailing closures manually, so how would that work? Is the grammar unambiguous enough to offer suggestions when I start typing the same of another closure parameter? For such a significant change to the language I'd say a solution here would be required for real adoption. (In fact, perhaps it should be something all proposals have to consider in the future.)



I like this much better than the first version, and I think I could come to terms with it, although the confusing way this interacts with default arguments seems like it would be annoying to library authors who'd have to jump in and add additional overloads to make their APIs usable, and confusing to users who don't understand the quite complex rules. And that will remain until we get a chance to fix it in a new language mode, whenever that will come to pass.

Overall though, I don't think this goes far enough to be worth it, and I think there are two directions which I would like to see explored:

  1. Apply the proposed syntax to all arguments:

    I think it is beneficial to break out long closures without having them surrounded by punctuation, but I believe the same thing applies to longer normal parameters (e.g. a call to an initializer with multiple arguments, which is itself broken into multiple lines), or just a large number of smaller parameters. Maybe allow omitting the comma in multi-line argument lists while we're at it.

    This would end up similar to one of the more "crazy" examples of what Chris described in the first review thread, which looks quite good to me.

  2. Have a special syntax for closures, but make it feel like building syntax:

    This would be different enough to warrant a completely new proposal, and is a bit more out there, but if we do want special syntax for closures alone, I'd much rather we expand on the precedent of allowing library-authors to build syntax-like constructs, which would mean dropping the : and allowing some way to pass parameters to the "labels" of closures after the first one (which would of course really be passed to the original function invocation).

    I guess—but do now know for certain—this should be parseable, as it is just like saying "there is this other function that takes a trailing closure, but you are only allowed to call it right after calling the original function". Please correct me if I'm wrong on this though :)

In its current form, barely. I don't think having to wrap the whole parameter list, including closures, in () and maybe dropping in a few line-breaks is all too bad for either readability or writability. Omitting those is quite nice from an aesthetic standpoint, but I don't think it's worth it if we're just special-casing closures in a weird way.

Not in my eyes, as I really like the concept of defining syntax-like constructs in library code, and this moves trailing closures away from that direction. If this was just a general thing you could do with argument lists, I'd be okay with it, but as is I don't think it makes sense.

Ruby allows omitting parens around argument lists, and I like that feature very much. Other than that no.

I read both versions of the proposal and loosely followed both review threads, but I've not done that deep a dive on it.


It seems to me there is no loss of clarity because the base name of the method animate describes what the primary closure is doing.

Whereas looking at just the base name of drop:

text.drop { $0.whitespace }

... it's unclear whether this is dropping while there is whitespace or where there is whitespace.

You may have memorized the stdlib surface area and know that drop(where:) doesn't exist yet, but it's a natural algorithm to include as part of a follow up to SE-0270 that adds closure predicate variants of the algorithms.


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.