Custom iterators & performance tips
Implement custom iterators/sequences and keep them efficient: single-pass behavior, avoiding extra allocations, and using lazy views.
Custom iterators 101
Create your own IteratorProtocol and Sequence. Iterators are usually single-pass and must return nil at the end.
IteratorProtocol example
Implement next() to yield one element per call and advance state; return nil to finish.
struct CountdownIterator: IteratorProtocol {
var current: Int
mutating func next() -> Int? {
guard current >= 0 else { return nil }
defer { current -= 1 } // advance state
return current
}
}
var it = CountdownIterator(current: 3)
while let n = it.next() { print(n, terminator: " ") } // 3 2 1 0
print("")All lessons in this course
- Sequence/Collection hierarchies
- Map/Filter/Reduce, lazy sequences
- Custom iterators & performance tips