SE-0279: Multiple Trailing Closures [Amended]

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.

12 Likes

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:

pointFromClosures
    _: { 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 {
  1
} _: {
  2
} _: {
  3
}

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

pointFromClosures
{ 1 } 
{ 2 }
{ 3 }

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

pointFromClosures
{ 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
  self.view.removeFromSuperview()
}

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.

16 Likes

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?

2 Likes

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.

2 Likes

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.

N/A

Followed all the threads.

4 Likes

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.

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

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.)

10 Likes

-0.5

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.

5 Likes

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.

2 Likes

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:

UIView.animate<CURSOR>

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.

11 Likes

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

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

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

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

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

regards,

Lars

7 Likes

+1

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

+0.5
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.

4 Likes

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

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

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

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

@Lantua already mentioned this briefly above.

11 Likes