alltom
alltom

Reputation: 3252

How do you map over the values of Zip2?

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?

Upvotes: 5

Views: 1149

Answers (2)

fqdn
fqdn

Reputation: 2843

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]

Upvotes: 6

GoZoner
GoZoner

Reputation: 70175

Assume that vals is the result of Zip2, which I'll presume is an array of two tuples. Like this:

let vals = [(1, "a"), (2, "b"), (3, "c")]

With that, just invoke the map() method on an array.

vals.map { $0.0 }

For example:

> vals.map { $0.1 }
$R16: String[] = size=3 {
  [0] = "a"
  [1] = "b"
  [2] = "c"
}

Upvotes: 0

Related Questions