-
-
Save wookiee/6c50522a29a58c07c95b2d0d2fa58458 to your computer and use it in GitHub Desktop.
Implementing zip3 in Swift
This file contains hidden or 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 Zip3Iterator | |
< | |
A: IteratorProtocol, | |
B: IteratorProtocol, | |
C: IteratorProtocol | |
>: IteratorProtocol { | |
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(), let b = second.next(), let c = third.next() { | |
return (a, b, c) | |
} | |
return nil | |
} | |
} | |
func zip<A: Sequence, B: Sequence, C: Sequence>(a: A, b: B, c: C) -> IteratorSequence<Zip3Iterator<A.Iterator, B.Iterator, C.Iterator>> { | |
return IteratorSequence(Zip3Iterator(a.makeIterator(), b.makeIterator(), c.makeIterator())) | |
} | |
// Use the zip | |
let iterator: Zip3Iterator = zip([1, 2, 3], ["test", "foo", "bar"], [2.2, 3.14, 5, 22]) | |
// Make an array from it | |
let result: Array<(Int,String,Double)> = Array(iterator) | |
// Iterate over it | |
for triplet in iterator { | |
print("\(triplet.0) is related to \(triplet.1) and \(triplet.2)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated for Swift 4 compat