The Sequence protocol lets you create your own collections that can be looped over with a for-in loop. It helps you make custom lists that work like arrays.
0
0
Sequence protocol for custom iteration in Swift
Introduction
When you want to make a custom list of items that can be looped through easily.
When you have a special data structure and want to use <code>for-in</code> loops on it.
When you want to control how items are given one by one from your collection.
When you want to create a sequence that generates values on the fly, like numbers or dates.
Syntax
Swift
struct MySequence: Sequence { func makeIterator() -> some IteratorProtocol { // return an iterator here } } struct MyIterator: IteratorProtocol { mutating func next() -> Element? { // return next element or nil } }
You must provide a makeIterator() method that returns an iterator.
The iterator must have a next() method that returns the next item or nil when done.
Examples
This example creates a countdown sequence from a start number down to zero.
Swift
struct CountDown: Sequence { let start: Int func makeIterator() -> CountDownIterator { CountDownIterator(current: start) } } struct CountDownIterator: IteratorProtocol { var current: Int mutating func next() -> Int? { if current < 0 { return nil } defer { current -= 1 } return current } }
This example creates a sequence of even numbers up to a max value using a closure-based iterator.
Swift
struct EvenNumbers: Sequence { let max: Int func makeIterator() -> AnyIterator<Int> { var current = 0 return AnyIterator { guard current <= max else { return nil } let result = current current += 2 return result } } }
Sample Program
This program counts down from 3 to 0 by looping over a custom sequence.
Swift
struct CountDown: Sequence { let start: Int func makeIterator() -> CountDownIterator { CountDownIterator(current: start) } } struct CountDownIterator: IteratorProtocol { var current: Int mutating func next() -> Int? { if current < 0 { return nil } defer { current -= 1 } return current } } let countdown = CountDown(start: 3) for number in countdown { print(number) }
OutputSuccess
Important Notes
Use mutating on next() because it changes the iterator's state.
Returning nil from next() means the sequence ended.
You can use AnyIterator to simplify iterator creation with closures.
Summary
The Sequence protocol lets you make custom collections that work with for-in loops.
You must provide an iterator with a next() method that returns items or nil.
This helps you create flexible and reusable ways to loop over your own data.