Skip to content

Instantly share code, notes, and snippets.

@JRHeaton
Created February 19, 2015 08:46
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JRHeaton/ff5addcd72f221dd57ad to your computer and use it in GitHub Desktop.
Save JRHeaton/ff5addcd72f221dd57ad to your computer and use it in GitHub Desktop.
Implementing zip3 in Swift
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]))
@twof
Copy link

twof commented Mar 28, 2018

Updated for Swift 4

struct Zip3Generator
    <
    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
    }

    // swiftlint:disable large_tuple
    mutating func next() -> (A.Element, B.Element, C.Element)? {
        if let first = first.next(), let second = second.next(), let third = third.next() {
            return (first, second, third)
        }
        return nil
    }
}

func zip<A: Sequence, B: Sequence, C: Sequence>(_ first: A, _ second: B, _ third: C) -> IteratorSequence<Zip3Generator<A.Iterator, B.Iterator, C.Iterator>> {
    return IteratorSequence(Zip3Generator(first.makeIterator(), second.makeIterator(), third.makeIterator()))
}

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