tuple decomposition wildcard

695 views Asked by At

Let's say you have this tuple

let tuple = (1,2,3,4)

You can "decompose" it by doing this

let (a,b,c,d) = tuple

And then use the individual variables a, b, c, d however you need.

You can use the placeholder _ for values in the tuple you don't need.

let (a,b,_,_) = tuple

So, you're ignoring everything but the first two values.

What if the tuple has a lot of elements? For example MIDIPacket has a data tuple that has 128 values. Most MIDI messages have only a handful of data; often only 3. If would be nice to decompose only those 3 and ignore the rest.

Like this:

let (status, note, velocity, _) = packet.data

Swift nopes out of that. You need a _ for each value.

Unless I'm missing a wildcard syntax. Am I?

let (status, note, velocity, _*) = packet.data

Would be nice (but this doesn't work).

1

There are 1 answers

1
Race B On

Using your simple example could you do something like this:

let tuple = (1,2,3,4)
let (a,b,c,d) = tuple
let (x,y) = (tuple.0,tuple.1)

If you know the elements on the tuple and there are three specifics ones you want then this should work. If you don't know which ones contain data then you would like need to write a func to go through the tuple, etc