Iterators, sequences, and collections
The Swift standard library provides several built-in collection types that we looked at back in Chapter 2, Working with Commonly Used Data Structures. The Swift language runtime provides several language features for working with collections, such as subscripts for shortcuts to access collection elements, and for…in
control flow for iterating over collections. By conforming to the built-in protocols, IteratorProtocol
, Sequence
, and Collection
, your custom collection types will gain the same type of access the common language constructs use when using subscript and for…in
syntax as native Swift collection types.
Iterators
An iterator is any type that conforms to the IteratorProtocol
protocol. The sole purpose of IteratorProtocol
is to encapsulate the iteration state of a collection by providing the next()
method, which iterates over a collection, returning the next element in a sequence or nil if the end has been reached.
The IteratorProtocol
protocol is...