Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Pair Generator
/*
* Allows iteration over pairs of a series
* This is useful for comparing or performing actions on
* adjacent items in an array
*/
struct PairingGenerator<Generator: GeneratorType>: GeneratorType {
var generator: Generator
var previous: Generator.Element?
let first: Generator.Element?
init(generator: Generator, looparound: Bool){
self.generator = generator
self.previous = self.generator.next()
self.first = looparound ? previous : nil
}
mutating func next() -> (Generator.Element, Generator.Element)? {
if let previous = previous, let next = self.generator.next() {
let pair = (previous, next)
self.previous = next
return pair
}
else if let first = first, let previous = previous {
self.previous = nil
return (previous, first)
}
else {
return nil
}
}
}
struct PairSequence<Sequence: SequenceType>: SequenceType {
let sequence: Sequence
let looparound: Bool
init(sequence: Sequence, looparound: Bool = false){
self.sequence = sequence
self.looparound = looparound
}
func generate() -> PairingGenerator<Sequence.Generator> {
return PairingGenerator(generator: sequence.generate(), looparound: looparound)
}
}
extension SequenceType {
func pairs(looparound: Bool = false) -> PairSequence<Self> {
return PairSequence(sequence: sequence, looparound: looparound)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.