There is already a function for that called Zip2
:
var first = [0,1,2,3]
var second = ["zero", "one", "two", "three"]
Array(Zip2(first,second))
// (0, "zero"), (1, "one"), (2, "two"), (3, "three")
This function however does not pad with nil and it also uses the shortest of the two passed in sequences. Notice though that it does not require that the types match between the two sequences and that it takes any sequence, not just arrays.
Here is my own custom implementation of Zip2WithNilPadding:
struct Zip2WithNilPadding<T: SequenceType,U: SequenceType>: SequenceType {
typealias Generator = GeneratorOf<(T.Generator.Element?, U.Generator.Element?)>
let first: T
let second: U
init(_ first: T, _ second: U) {
self.first = first
self.second = second
}
func generate() -> Generator {
var generator1: T.Generator? = first.generate()
var generator2: U.Generator? = second.generate()
return GeneratorOf<(T.Generator.Element?, U.Generator.Element?)>() {
let element1 = generator1?.next()
let element2 = generator2?.next()
if element1 == nil && element2 == nil {
return nil
}
else if element1 == nil{
generator1 = nil
}
else if element2 == nil {
generator2 = nil
}
return (element1, element2)
}
}
}
var first = [0,1,2]
var second = ["zero", "one", "two", "three", "four"]
Array(Zip2WithNilPadding(first, second))
If you have questions about the specific implementation let me know and I will try to clarify. This implementation should also help you in creating a Zip that takes an array of sequences. Unfortunately in that case they would all have to be a sequence of the same type because you can't have a variable amount of generics.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…