[swift-evolution] [Pitch] Tuple Destructuring in Parameter Lists

Matthew Johnson matthew at anandabits.com
Mon May 30 09:14:32 CDT 2016



Sent from my iPad

On May 30, 2016, at 8:01 AM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:

>> // Allowed today:
>> func takesATuple(tuple: (Int, Int)) {
>>  let valueA = tuple.0
>>  let valueB = tuple.1
>>  // ...
>> }
>> 
>> // Proposed syntax:
>> func takesATuple(tuple (valueA, valueB): (Int, Int)) {
>>  // use valueA
>>  // use valueB
>> }
> 
> Personally, I find this example confusing because the label is "tuple", which kind of reads like a keyword, and because you're using the same name for the label and variable. If I understand the semantics you're proposing correctly, I think it would be clearer to write this example like:
> 
> // Allowed today:
> func takes(a tuple: (Int, Int)) {
>  let valueA = tuple.0
>  let valueB = tuple.1
>  // ...
> }
> 
> // Proposed syntax:
> func takes(a (valueA, valueB): (Int, Int)) {
>  // use valueA
>  // use valueB
> }
> 
> Incidentally, it may also be a good idea to define what happens if you write:
> 
> func takes((valueA, valueB): (Int, Int))
> 
> Normally, if there's no separate label and variable name, they're the same, but you can't have a label like `(valueA, valueB)`. I see two reasonably sensible answers here:
> 
> 1. It's equivalent to writing `_ (valueA, valueB)`.
> 2. It's illegal. You have to write a label, or `_` if you don't want one.
> 
> My preference would be for #2, but you're the designer, not me.

I agree.  #2 is more consistent with Swift 3 where all arguments have external names by default.  I don't think this should change just because there is no direct internal name that can also serve as an external name.

I like the idea of allowing destructuring everywhere we bind a name very much.  My only (minor) concern with doing this for tuples right now is that it might encourage overuse of them where a struct would be a better choice.  

I have been thinking about destructuring of structs and classes and wonder if it might be best to introduce that first.  That would avoid any temptation to abuse tuples just because they can be destructured.  This is probably an overblown concern but it is something to consider.   

Another option would be to just introduce a related proposal to destructure structs and classes at roughly the same time as the parameter destructuring proposal...

> 
> -- 
> Brent Royal-Gordon
> Architechies
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list