A type that iterates over a collection using its indices.

@frozen struct IndexingIterator<Elements> where Elements : Collection


The IndexingIterator 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 IndexingIterator as their iterator.

By default, any custom collection type you create will inherit a makeIterator() method that returns an IndexingIterator 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 makeIterator() method satisfies the requirements of the Sequence protocol.

Here’s an example of a type that declares the minimal requirements for a collection. The CollectionOfTwo 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 CollectionOfTwo doesn’t define its own makeIterator() method or Iterator associated type, it uses the default iterator type, IndexingIterator. This example shows how a CollectionOfTwo 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 {
// Prints "15.0"
// Prints "20.0"



Instance Properties

  • var lazy: LazySequence<Self>

    A sequence containing the same elements as this sequence, but on which some operations, such as map and filter, are implemented lazily.

  • var underestimatedCount: Int

    A value less than or equal to the number of elements in the sequence, calculated nondestructively.

Instance Methods

Conforms To

Removed Members