Home > Back-end >  Swift Extended iterable unpacking of tuples
Swift Extended iterable unpacking of tuples

Time:01-09

We know in Python you can do

s = (3,5,2)
a, *b = s # a=3 b=[5,2]

That is, you can unpack let's say the first element of the tuple and the rest.

I'm struggling to find the same in Swift:

var tuple = ("Boston", "Red Sox", 97, 65, 59.9)
var (first, rest) = tuple

CodePudding user response:

There is none (at the moment), Swift is strongly typed. i.e the compiler has to know this information - you can write a function that does the unpacking though.

func unpack(tuple: (String, String, Double, Double, Double)) -> (String, (String, Double, Double, Double)) {
  return (tuple.0,(tuple.1, tuple.2, tuple.3, tuple.4))
}

In case you have more than two/three elements in a tuple it is recommended to group them under some model.

CodePudding user response:

You could make some generic functions to do it:

func firstRest<A, B, C>(_ tup: (A, B, C)) -> (A, (B, C)) {
    (tup.0, (tup.1, tup.2))
}

func firstRest<A, B, C, D>(_ tup: (A, B, C, D)) -> (A, (B, C, D)) {
    (tup.0, (tup.1, tup.2, tup.3))
}

func firstRest<A, B, C, D, E>(_ tup: (A, B, C, D, E)) -> (A, (B, C, D, E)) {
    (tup.0, (tup.1, tup.2, tup.3, tup.4))
}

func firstRest<A, B, C, D, E, F>(_ tup: (A, B, C, D, E, F)) -> (A, (B, C, D, E, F)) {
    (tup.0, (tup.1, tup.2, tup.3, tup.4, tup.5))
}

Now you can:

let tuple = ("Boston", "Red Sox", 97, 65, 59.9)
let (first, rest) = firstRest(tuple)
print(first)
print(rest)
  •  Tags:  
  • Related