Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bound a sequence with a start and end marker
struct BoundedSequence<Base: Sequence> {
let _base: Base
}
extension BoundedSequence {
struct Iterator {
enum State { case starting, iterating, ended }
var _state: State
var _iterator: Base.Iterator
}
}
extension BoundedSequence.Iterator: IteratorProtocol {
enum Element {
case start, end
case middle(Base.Element)
}
mutating func next() -> Element? {
switch _state {
case .starting:
_state = .iterating
return .start
case .iterating:
if let x = _iterator.next() {
return .middle(x)
} else {
_state = .ended
return .end
}
case .ended: return nil
}
}
}
extension BoundedSequence: Sequence {
func makeIterator() -> Iterator {
return Iterator(_state: .starting, _iterator: _base.makeIterator())
}
}
extension Sequence {
func bounded() -> BoundedSequence<Self> {
return BoundedSequence(_base: self)
}
}
for bounded in "foo".bounded() {
switch bounded {
case .start: print("started")
case .middle(let x): print(x)
case .end: print("ended")
}
}
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.