Iterator Pattern Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Iterator Pattern runs in O(n) time and O(1) space, in Swift as in every other language.
- ✓Two protocols cooperate: IteratorProtocol requires mutating func next() -> Element?, and Sequence requires makeIterator().
- ✓Conform your container to Sequence and return a fresh iterator from makeIterator(). If your type can be walked repeatedly and knows its own count, conform to Collection instead, you gain count, indices, subscripting and random access, and Sequence alone deliberately promises none of those.
- ✓The Swift trap: Sequence explicitly does NOT guarantee multi-pass: the documentation warns that a sequence may be consumed by iteration, so writing a generic function over Sequence that walks its argument twice is correct for arrays and silently wrong for a single-pass sequence, constrain to Collection when you need to walk twice.
- ✓For a struct iterator in a release build the optimiser specialises the generic and inlines next() into the loop, so a for-in over an Array compiles to a plain indexed loop with retain/release traffic eliminated for value types.
What Iterator Pattern actually is
Iterator Pattern in Swift: what you actually reach for
Swift implementation
struct Ring: Sequence {
let items: [Int]
// Sequence gives you map/filter/reduce for free once this exists.
func makeIterator() -> AnyIterator<Int> {
var i = 0
return AnyIterator {
guard i < items.count else { return nil }
defer { i += 1 }
return items[i]
}
}
}
let r = Ring(items: [1, 2, 3, 4])
print(Array(r)) // [1, 2, 3, 4]
print(r.filter { $0 % 2 == 0 }) // [2, 4]
// Sequence does NOT promise multi-pass. If you must walk twice,
// constrain to Collection instead:
func firstAndCount<C: Collection>(_ c: C) -> (C.Element?, Int) {
(c.first, c.count) // safe: Collection is multi-pass
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Iterator Pattern?
Two protocols cooperate: IteratorProtocol requires mutating func next() -> Element?, and Sequence requires makeIterator(). Conform to Sequence and you inherit map, filter, prefix, reduce and the rest for free, exactly as Rust gives you adapters from Iterator. AnyIterator wraps a closure when you do not want a named type, and AsyncSequence with AsyncIteratorProtocol is the await-driven twin consumed by for await.
What is the most common Swift mistake when implementing Iterator Pattern?
Sequence explicitly does NOT guarantee multi-pass: the documentation warns that a sequence may be consumed by iteration, so writing a generic function over Sequence that walks its argument twice is correct for arrays and silently wrong for a single-pass sequence, constrain to Collection when you need to walk twice. Related, calling count or isEmpty on a bare Sequence can consume it or be O(n), which is why those live on Collection. And an AsyncSequence dropped without cancellation keeps its underlying task alive.
How does Iterator Pattern actually perform in Swift?
For a struct iterator in a release build the optimiser specialises the generic and inlines next() into the loop, so a for-in over an Array compiles to a plain indexed loop with retain/release traffic eliminated for value types. Two things kill that: existential types (any Sequence) which force dynamic dispatch per element, and reference-typed elements whose ARC retain/release cannot be elided. AnyIterator adds a closure call per element and should stay out of hot loops. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.