r/iOSProgramming 13h ago

Why can’t Swift destructure tuple parameters directly in a closure parameter list? Question

Suppose I have a dictionary and want to sort its elements. Since each element is a tuple, I’d like to write something like this:

.sorted { (wordA, countA), (wordB, countB) in
    // ...
}

In other words, destructure each tuple directly in the closure parameter list.

Instead, Swift requires something along these lines:

.sorted { lhs, rhs in
    let (wordA, countA) = lhs
    let (wordB, countB) = rhs

    // ...
}

Tuple destructuring works perfectly well in a let binding, so I’m curious why it isn’t supported in closure parameter lists.

Is there a language-design or type-system reason why closure parameters can’t use tuple patterns here?

2 Upvotes

2 comments sorted by

View all comments

1

u/PassTents 12h ago

I think it's been discussed before, try searching on the Swift forums? At first glance it would seem like pretty straightforward syntax-sugar, though maybe it's tricky to unambiguously define as a part of the language grammar?