Skip to content

Instantly share code, notes, and snippets.

@sveinhal
Last active August 29, 2015 14:24
Show Gist options
  • Save sveinhal/57a0bc2e2fae6cb064c7 to your computer and use it in GitHub Desktop.
Save sveinhal/57a0bc2e2fae6cb064c7 to your computer and use it in GitHub Desktop.
A sequence type that iterates over pairs of the underlying sequence
import Foundation
struct PairGenerator<T: GeneratorType> : GeneratorType {
typealias Pair = (first: T.Element?, second: T.Element?)
var baseGenerator: T
var previousPair: Pair
init(_ baseGenerator: T) {
self.baseGenerator = baseGenerator
self.previousPair = (nil, nil)
}
mutating func next() -> Pair? {
let pair = (first: previousPair.second, second: baseGenerator.next())
previousPair = pair
if pair.first == nil && pair.second == nil {
return nil
} else {
return pair
}
}
}
extension SequenceType {
func pairs() -> GeneratorSequence<PairGenerator<Self.Generator>> {
return GeneratorSequence(PairGenerator(generate()))
}
}
@sveinhal
Copy link
Author

sveinhal commented Jul 3, 2015

Given any SequenceType this adds a method pairs() which returns another kind of SequenceType. It lets you iterate over pairs in a sequence, like so:

let words = ["good", "morning", "swift"]
for (a, b) in words.pairs() {
    print("\(a), \(b)")
    // nil, "good"
    // "good", "morning"
    // "morning", "swift"
    // "swift", nil
}

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