Skip to content

Instantly share code, notes, and snippets.

@SteveTrewick
Last active March 2, 2019 18:49
Show Gist options
  • Save SteveTrewick/13978e794eb26959f9126e81a807a4ac to your computer and use it in GitHub Desktop.
Save SteveTrewick/13978e794eb26959f9126e81a807a4ac to your computer and use it in GitHub Desktop.
When you just really need both the current and next elements in a swift sequence
import Foundation
struct PeekAheadIterator<T> {
let elements:[T]
public init(elements:[T]) {
self.elements = elements
}
func each(closure:(T,T?)->Void) {
var iterator = elements.makeIterator()
var current = iterator.next()
var next = iterator.next()
while let current_ = current {
closure(current_ , next)
current = next
next = iterator.next()
}
}
}
let peekahead = PeekAheadIterator(elements: [1,2,3,4,5,6,7])
peekahead.each { current, next in
print("\(current), \(next)")
}
/*
1, Optional(2)
2, Optional(3)
3, Optional(4)
4, Optional(5)
5, Optional(6)
6, Optional(7)
7, nil
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment