Skip to content
Commitwise
Menu

Iterator pattern

A way to go through a collection's elements one at a time without knowing how the collection stores them.

Definition

The collection creates a fresh iterator for each traversal, and the iterator keeps the position. Swift Sequence, Kotlin and Java Iterable and TypeScript's Symbol.iterator are built-in forms, so implementing them makes for loops work. Lazy and async iterators (generators, Flow, AsyncSequence) produce elements only when asked, which suits paged APIs. A collection must not be modified while it is being iterated.

In practice

for query in recentSearches walks a ring buffer newest first without exposing its array or index.

Related terms

Esc

Type to search the whole site.