Labeled trailing closures

Is there any appetite for allowing argument labels to be applied to the first trailing closure of a call expression? As things are now, we have to choose between indenting all closure arguments:

presentDeletionModal(
    for: selectedDocument,
    onConfirm: {
        // ...
    },
    onCancel: {
        // ...
    }
)

or forgoing a potentially illuminating argument label for the first trailing closure argument:

presentDeletionModal(
    for: selectedDocument
) {
    // ...
} onCancel: {
    // ...
}

I would often prefer:

presentDeletionModal(
    for: selectedDocument
) onConfirm: {
    // ...
} onCancel: {
    // ...
}
13 Likes

@xwu had a syntax for this back when trailing closures were first reviewed, and this was a huge point of contention during the review. Personally I'd still appreciate it.

11 Likes

This looks nice but I wonder if it introduces more ambiguity... which trailing closure review was it discussed in @Jon_Shier?

I don't remember that specific comment, but it would have almost certainly been in the second review of SE-0279.

https://forums.swift.org/t/support-use-of-an-optional-label-for-the-first-trailing-closure/36371/13

7 Likes

https://forums.swift.org/t/principles-for-trailing-closure-evolution-proposals/37265

6 Likes

:upside_down_face: :upside_down_face:

4 Likes

How would that look without the "for: selectedDocument" parameter, like so?

presentDeletionModel() onConfirm: {} onCancel: {}

Note that with the normal unlabelled trailing closure the () are optional, but here it would probably not work:

presentDeletionModel onConfirm: {} onCancel: {}

Why wouldn't it?

There are very few places in expression grammars where two identifiers are juxtaposed, and many of them revolve around disambiguating contextual keywords (like copy x treats copy as a keyword but copy(x) treats it as an identifier). I suspect a parser rule that treats <expr> <identifier>: as a no-arg call followed by a trailing closure label would be unambiguous.

4 Likes

Hahaha yep... looks like we've arrived at the can we kicked down the road :sweat_smile:

6 Likes

You are right, it feels unusual but could actually work.

1 Like

I don't remember if I mentioned it at the time, but I'm definitely for this. Every now and then I try this and and am always disappointed that it doesn't work.

3 Likes

at least offering the option to add a label to the first closure would be something I appreciate very much.

2 Likes

That’s all that’s on the table - changes that break preexisting code are very problematic at this point, and only accepted if the problem they solve is even worse

3 Likes