Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you map over the values of Zip2?

Tags:

swift

I have two arrays like [1, 2, 3] and ["a", "b", "c"] and I want to map over the zipped values (1, "a"), (2, "b"), and (3, "c") using Zip2.

If I do this:

let foo = map(Zip2([1, 2, 3], ["a", "b", "c"]).generate()) { $0.0 }

foo has the type ZipGenerator2<IndexingGenerator<Array<Int>>, IndexingGenerator<Array<String>>>?.

Is there a way to make that an array?

like image 288
alltom Avatar asked Jun 23 '14 03:06

alltom


1 Answers

The following will get you an array from the return value of Zip2:

var myZip = Zip2([1, 2, 3], ["a", "b", "c"]).generate()
var myZipArray: Array<(Int, String)> = []

while let elem = myZip.next() {
    myZipArray += elem
}

println(myZipArray)    // [(1, a), (2, b), (3, c)]

-- UPDATE: EVEN BETTER! --

let myZip = Zip2([1, 2, 3], ["a", "b", "c"])
let myZipArray = Array(myZip)

println(myZipArray)    // [(1, a), (2, b), (3, c)]

-- now for fun --

I'm going to guess that we can init a new Array with anything that responds to generate() ?

println(Array("abcde"))  // [a, b, c, d, e]
like image 131
fqdn Avatar answered Jan 02 '23 11:01

fqdn