A type that iterates over a collection using its indices.
SDK
- Xcode 8.0+
Framework
- Swift Standard Library
Declaration
@frozen struct IndexingIterator<Elements> where Elements : Collection
Overview
The Indexing
type is the default iterator for any collection that doesn’t declare its own. It acts as an iterator by using a collection’s indices to step over each value in the collection. Most collections in the standard library use Indexing
as their iterator.
By default, any custom collection type you create will inherit a make
method that returns an Indexing
instance, making it unnecessary to declare your own. When creating a custom collection type, add the minimal requirements of the Collection
protocol: starting and ending indices and a subscript for accessing elements. With those elements defined, the inherited make
method satisfies the requirements of the Sequence
protocol.
Here’s an example of a type that declares the minimal requirements for a collection. The Collection
structure is a fixed-size collection that always holds two elements of a specific type.
struct CollectionOfTwo<Element>: Collection {
let elements: (Element, Element)
init(_ first: Element, _ second: Element) {
self.elements = (first, second)
}
var startIndex: Int { return 0 }
var endIndex: Int { return 2 }
subscript(index: Int) -> Element {
switch index {
case 0: return elements.0
case 1: return elements.1
default: fatalError("Index out of bounds.")
}
}
func index(after i: Int) -> Int {
precondition(i < endIndex, "Can't advance beyond endIndex")
return i + 1
}
}
Because Collection
doesn’t define its own make
method or Iterator
associated type, it uses the default iterator type, Indexing
. This example shows how a Collection
instance can be created holding the values of a point, and then iterated over using a for
-in
loop.
let point = CollectionOfTwo(15.0, 20.0)
for element in point {
print(element)
}
// Prints "15.0"
// Prints "20.0"