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:
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:
Arguably this could be split into succeed closure and error closure, but it could also use Result type, or even async-await.
DSL
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.
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.
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
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.
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.
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.
Thanks for pointing it out. I was thinking it wrong. I was thinking in terms of having labels being the default, and @implicit for when the labels can be omitted. So, instead of the compiler looking for the function parameter corresponding to the first trailing closure and omitting its label requirement, the compiler can just omit whichever one that's annotated with @implicit. However, this is the opposite to what Michel proposed. Sorry for the confusion.
Let's put SE-0279 aside for a second. The existing rule effectively discourages a class of APIs from being written in the most natural way β to work with trailing-closure syntax, they have to use overloading instead of default arguments. That is something many people would like to fix in the future, but it will require a source-compatibility break, which will need to be separately investigated, proposed, and reviewed.
Nothing we can do in SE-0279 will meaningfully change any of that. Most APIs with defaultable parameters of function type can be called with a single closure argument, defaulting all the others. We cannot change the rule for how such a call is type-checked without breaking source compatibility, which means that API authors will continue to have to use overloading rather than default arguments to express these APIs. We will still have a problem we need to fix.
The degree of implementation challenge is not something we ask the Evolution community for feedback on, but in this case, no, it was not particularly challenging, once we accepted that we couldn't get around the inherent limitations imposed by the existing rule.
These rules seem to work well in practice, because functions with multiple closure arguments tend to have one that is more primary. Often any additional closure arguments are optional (via default parameter values or overloading), in order to provide progressive disclosure
Even thought there is some truth to that some "functions with multiple closure arguments tend to have one that is more primary", it doesn't justify the rule. The primary parameter doesn't necessarily happen to be the first parameter in a function declaration. And, regardless of that, the primary parameter's value doesn't necessarily happen to be the first trailing closure. This is clearly shown in the proposal's own examples:
ipAddressPublisher
.sink(receiveCompletion: { completion in
// handle error
}) { identity in
self.hostnames.insert(identity.hostname!)
}
The proposal uses the examples above to show that since the first parameters are the primary ones in the functions, the first trailing closures should have their labels omitted. However, the examples above (which will still be allowed if the proposal is accepted) clearly show that not all first trailing closures are the primary parameter values.
(This is what I was proposing on this other thread regarding single trailing closures.)
It'd would make the completion label mandatory. You'd only have these options for calling this function (or you get a warning):
UIView.animate(withDuration: 0.3) {
self.view.alpha =0
} completion: {
self.view.removeFromSuperview()
}
// or:
UIView.animate(withDuration: 0.3, animations: {
self.view.alpha =0
}, completion: {
self.view.removeFromSuperview()
})
// or (if we allow the first trailing closure to have a label):
UIView.animate(withDuration: 0.3) animations: {
self.view.alpha =0
} completion: {
self.view.removeFromSuperview()
}
So you'd be limited to all the options that actually make sense. ;-)
It'd also solve the Binding(get:set:) problem if you could make @explicit the two parameter labels.
Strictly speaking it's not source-breaking or backward-incompatible to make every label explicit by default if a failure to add the completion label only brings a warning (with a fixit). It'd just be deeply annoying because it'll happen for every call with a trailing closure where the closure parameter has a label... until the corresponding function signature is updated to make the label optional (where it makes sense).
That's probably fine for the standard library functions and I guess the Apple SDKs since they are updated in sync with the compiler. I assume Xcode's migration assistant would help too. Still, it'd be a disturbing change with a lot of trouble for everybody. Keeping the current behavior (optional label for the trailing closure) and adding a flag for when the label is required is easier and probably good enough, even though I think it's less in line with the language's principles.
I also tend to agree it'd be better if the label could not be omitted as a default behavior, but I disagree that the behavior should be different from the single trailing closure case. In particular, if we add mechanism like the @explicit attribute to prevent a label from being omitted as a single closure, it'd be quite awkward that we also had to add an @implicit attribute to allow a parameter label to be omitted in the multiple closure case.
Yes, although I must point out that it's not just a matter of whether a label is provided; source compatibility does require the choice of which parameter to pass the closure as to not change.