Skip to content

Instantly share code, notes, and snippets.

@wookiee
Forked from JRHeaton/zip3.swift
Last active February 5, 2018 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wookiee/6c50522a29a58c07c95b2d0d2fa58458 to your computer and use it in GitHub Desktop.
Save wookiee/6c50522a29a58c07c95b2d0d2fa58458 to your computer and use it in GitHub Desktop.
Implementing zip3 in Swift
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)")
}
@wookiee
Copy link
Author

wookiee commented Feb 5, 2018

Updated for Swift 4 compat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment