Sequence

    A type that provides sequential, iterated access to its elements.

    protocol Sequence<Element>
    Browse conforming types

    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:

    let oneTwoThree = 1...3
    for number in oneTwoThree {
        print(number)
    }
    // Prints "1"
    // Prints "2"
    // Prints "3"

    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.

    let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
    var hasMosquito = false
    for bug in bugs {
        if bug == "Mosquito" {
            hasMosquito = true
            break
        }
    }
    print("'bugs' has a mosquito: \(hasMosquito)")
    // Prints "'bugs' has a mosquito: false"

    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:

    if bugs.contains("Mosquito") {
        print("Break out the bug spray.")
    } else {
        print("Whew, no mosquitos!")
    }
    // Prints "Whew, no mosquitos!"

    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:

    for element in sequence {
        if ... some condition { break }
    }
    
    for element in sequence {
        // No defined behavior
    }

    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 makeIterator() method that returns an iterator.

    Alternatively, if your type can act as its own iterator, implementing the requirements of the IteratorProtocol protocol and declaring conformance to both Sequence and IteratorProtocol are sufficient.

    Here’s a definition of a Countdown sequence that serves as its own iterator. The makeIterator() method is provided as a default implementation.

    struct Countdown: Sequence, IteratorProtocol {
        var count: Int
    
        mutating func next() -> Int? {
            if count == 0 {
                return nil
            } else {
                defer { count -= 1 }
                return count
            }
        }
    }
    
    let threeToGo = Countdown(count: 3)
    for i in threeToGo {
        print(i)
    }
    // Prints "3"
    // Prints "2"
    // Prints "1"

    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.

    Requirements

    Type members

    Instance members

    Citizens in Swift

    Instance members

    Show obsolete interfaces (1)

    Hide obsolete interfaces

    Subtypes

    Citizens in Swift

    where Self == Self.Iterator

    Instance members

    Citizens in Swift

    where Self.Element:Comparable

    Instance members

    Citizens in Swift

    where Self.Element:Equatable

    Instance members

    Citizens in Swift

    where Self.Element:Sequence

    Instance members

    Citizens in Swift

    where Self.Element:StringProtocol

    Instance members

    Available in _RegexParser

    Instance members

    Available in Cxx

    Subtypes

    Available in FoundationEssentials

    Instance members

    Subtypes

    Available in FoundationInternationalization

    Instance members

    Available in FoundationInternationalization

    where Self.Element == String

    Instance members

    Extension in Algorithms

    Instance members

    Show obsolete interfaces (3)

    Hide obsolete interfaces

    Extension in Algorithms

    where Self.Element:Hashable

    Instance members

    Extension in Algorithms

    where Self.Element:Comparable

    Instance members

    Extension in Algorithms

    where Self.Element:Sequence

    Instance members

    Extension in AsyncAlgorithms

    Instance members

    • var async: AsyncSyncSequence<Self>

      An asynchronous sequence containing the same elements as this sequence, but on which operations, such as map and filter, are implemented asynchronously.

    Extension in Crypto

    Subtypes

    Extension in _NIOFileSystem

    where Self:Sendable, Self.Element == UInt8

    Instance members

    Extension in PackageModel

    where Self.Element == Module

    Instance members

    Extension in Vapor

    where Self.Element == UInt8

    Instance members