Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a zip function to create tuples with more than 2 elements?

Tags:

swift

I just discovered the Swift zip function recently. It seems quite useful.

It takes 2 input arrays and creates an array of tuples out of pairs of values from each array.

Is there a variant of zip that takes an arbitrary number of arrays and outputs tuples with that same number of elements? It seems like there should be a way to do this.

like image 509
Duncan C Avatar asked Nov 09 '16 23:11

Duncan C


2 Answers

Bear in mind, you can nest one zip inside another, and then unpack it with a nested tuple:

let integers = [1, 2, 3, 4, 5]
let strings = ["a", "b", "c", "d", "e"]
let doubles = [1.0, 2.0, 3.0, 4.0, 5.0]

for (integer, (string, double)) in zip(integers, zip(strings, doubles)) {
    print("\(integer) \(string) \(double)")
}

Not quite as elegant as having a zip for arbitrary n-tuples, but it gets the job done.

like image 120
Airspeed Velocity Avatar answered Oct 11 '22 05:10

Airspeed Velocity


No, zip for an arbitrary number of sequences isn't currently possible due to Swift's lack of variadic generics. This is discussed in the Generics Manifesto.

In the meanwhile, I wrote a gyb template for generating ZipSequences of custom arity. I've also pre-generated ZipSequences of arity 3...10 for your convenience. It's available here.

In action:

let integers = [1, 2, 3, 4, 5]
let strings = ["a", "b", "c", "d", "e"]
let doubles = [1.0, 2.0, 3.0, 4.0, 5.0]

for (integer, string, double) in zip(integers, strings, doubles) {
    print("\(integer) \(string) \(double)")
}

Prints:

1 a 1.0

2 b 2.0

3 c 3.0

4 d 4.0

5 e 5.0

like image 27
Alexander Avatar answered Oct 11 '22 06:10

Alexander