A type that provides sequential, iterated access to its elements.
SDK
- Xcode 8.0+
Framework
- Swift Standard Library
Declaration
Overview
A sequence is a list of values that you can step through one at a time. The most common way to iterate over the elements of a sequence is to use a for
-in
loop:
While seemingly simple, this capability gives you access to a large number of operations that you can perform on any sequence. As an example, to check whether a sequence includes a particular value, you can test each value sequentially until you’ve found a match or reached the end of the sequence. This example checks to see whether a particular insect is in an array.
The Sequence
protocol provides default implementations for many common operations that depend on sequential access to a sequence’s values. For clearer, more concise code, the example above could use the array’s contains(_:)
method, which every sequence inherits from Sequence
, instead of iterating manually:
Repeated Access
The Sequence
protocol makes no requirement on conforming types regarding whether they will be destructively consumed by iteration. As a consequence, don’t assume that multiple for
-in
loops on a sequence will either resume iteration or restart from the beginning:
In this case, you cannot assume either that a sequence will be consumable and will resume iteration, or that a sequence is a collection and will restart iteration from the first element. A conforming sequence that is not a collection is allowed to produce an arbitrary sequence of elements in the second for
-in
loop.
To establish that a type you’ve created supports nondestructive iteration, add conformance to the Collection
protocol.
Conforming to the Sequence Protocol
Making your own custom types conform to Sequence
enables many useful operations, like for
-in
looping and the contains
method, without much effort. To add Sequence
conformance to your own custom type, add a make
method that returns an iterator.
Alternatively, if your type can act as its own iterator, implementing the requirements of the Iterator
protocol and declaring conformance to both Sequence
and Iterator
are sufficient.
Here’s a definition of a Countdown
sequence that serves as its own iterator. The make
method is provided as a default implementation.
Expected Performance
A sequence should provide its iterator in O(1). The Sequence
protocol makes no other requirements about element access, so routines that traverse a sequence should be considered O(n) unless documented otherwise.