Created
February 19, 2015 08:46
-
-
Save JRHeaton/ff5addcd72f221dd57ad to your computer and use it in GitHub Desktop.
Implementing zip3 in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Zip3Generator | |
< | |
A: GeneratorType, | |
B: GeneratorType, | |
C: GeneratorType | |
>: GeneratorType { | |
private var first: A | |
private var second: B | |
private var third: C | |
private var index = 0 | |
init(_ first: A, _ second: B, _ third: C) { | |
self.first = first | |
self.second = second | |
self.third = third | |
} | |
mutating func next() -> (A.Element, B.Element, C.Element)? { | |
if let a = first.next(), b = second.next(), c = third.next() { | |
return (a, b, c) | |
} | |
return nil | |
} | |
} | |
func zip<A: SequenceType, B: SequenceType, C: SequenceType>(a: A, b: B, c: C) -> GeneratorSequence<Zip3Generator<A.Generator, B.Generator, C.Generator>> { | |
return GeneratorSequence(Zip3Generator(a.generate(), b.generate(), c.generate())) | |
} | |
let x = Array(zip([1, 2, 3], ["test", "foo", "bar"], [2.2, 3.14, 5, 22])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated for Swift 4