Protocol

Sequence

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

Declaration

protocol Sequence

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:

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.

Topics

Creating an Iterator

func makeIterator() -> Self.Iterator

Returns an iterator over the elements of this sequence.

Required. Default implementations provided.

associatedtype Iterator

A type that provides the sequence’s iteration interface and encapsulates its iteration state.

Required.

associatedtype Element

A type representing the sequence’s elements.

Required.

Finding Elements

func contains(Self.Element) -> Bool

Returns a Boolean value indicating whether the sequence contains the given element.

func contains(where: (Self.Element) -> Bool) -> Bool

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

func first(where: (Self.Element) -> Bool) -> Self.Element?

Returns the first element of the sequence that satisfies the given predicate.

func min() -> Self.Element?

Returns the minimum element in the sequence.

func min(by: (Self.Element, Self.Element) -> Bool) -> Self.Element?

Returns the minimum element in the sequence, using the given predicate as the comparison between elements.

func max() -> Self.Element?

Returns the maximum element in the sequence.

func max(by: (Self.Element, Self.Element) -> Bool) -> Self.Element?

Returns the maximum element in the sequence, using the given predicate as the comparison between elements.

Transforming a Sequence

func compactMap<ElementOfResult>((Self.Element) -> ElementOfResult?) -> [ElementOfResult]

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

func flatMap<ElementOfResult>((Self.Element) -> ElementOfResult?) -> [ElementOfResult]

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

Deprecated
func flatMap<SegmentOfResult>((Self.Element) -> SegmentOfResult) -> [SegmentOfResult.Element]

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

func reduce<Result>(Result, (Result, Self.Element) -> Result) -> Result

Returns the result of combining the elements of the sequence using the given closure.

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.

Iterating Over a Sequence's Elements

func enumerated() -> EnumeratedSequence<Self>

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

Sorting Elements

func sorted() -> [Self.Element]

Returns the elements of the sequence, sorted.

func sorted(by: (Self.Element, Self.Element) -> Bool) -> [Self.Element]

Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.

func reversed() -> [Self.Element]

Returns an array containing the elements of this sequence in reverse order.

Splitting and Joining Elements

func joined() -> FlattenSequence<Self>

Returns the elements of this sequence of sequences, concatenated.

func joined(separator: String) -> String

Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.

func joined<Separator>(separator: Separator) -> JoinedSequence<Self>

Returns the concatenated elements of this sequence of sequences, inserting the given separator between each element.

Comparing Sequences

func elementsEqual<OtherSequence>(OtherSequence) -> Bool

Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.

func elementsEqual<OtherSequence>(OtherSequence, by: (Self.Element, OtherSequence.Element) -> Bool) -> Bool

Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements in the same order, using the given predicate as the equivalence test.

func starts<PossiblePrefix>(with: PossiblePrefix) -> Bool

Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.

func lexicographicallyPrecedes<OtherSequence>(OtherSequence) -> Bool

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (<) to compare elements.

func lexicographicallyPrecedes<OtherSequence>(OtherSequence, by: (Self.Element, Self.Element) -> Bool) -> Bool

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.

Publishing a Sequence

var publisher: Publishers.Sequence<Self, Never>

A Combine publisher that publishes each member of the sequence as a separate element.

Infrequently Used Functionality

func clip()

Instance Properties

var underestimatedCount: Int

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

Required. Default implementations provided.

Instance Methods

func allSatisfy((Self.Element) -> Bool) -> Bool

Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.

func drop(while: (Self.Element) -> Bool) -> DropWhileSequence<Self>

Returns a sequence by skipping the initial, consecutive elements that satisfy the given predicate.

func dropFirst(Int) -> DropFirstSequence<Self>

Returns a sequence containing all but the given number of initial elements.

func dropLast(Int) -> [Self.Element]

Returns a sequence containing all but the given number of final elements.

func fill(using: NSCompositingOperation)
func fill(using: NSCompositingOperation)
func fill(using: NSCompositingOperation)
func filter((Self.Element) -> Bool) -> [Self.Element]

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

func forEach((Self.Element) -> Void)

Calls the given closure on each element in the sequence in the same order as a for-in loop.

func map<T>((Self.Element) -> T) -> [T]

Returns an array containing the results of mapping the given closure over the sequence’s elements.

func prefix(Int) -> PrefixSequence<Self>

Returns a sequence, up to the specified maximum length, containing the initial elements of the sequence.

func prefix(while: (Self.Element) -> Bool) -> [Self.Element]

Returns a sequence containing the initial, consecutive elements that satisfy the given predicate.

func reduce<Result>(into: Result, (inout Result, Self.Element) -> ()) -> Result

Returns the result of combining the elements of the sequence using the given closure.

func shuffled() -> [Self.Element]

Returns the elements of the sequence, shuffled.

func shuffled<T>(using: inout T) -> [Self.Element]

Returns the elements of the sequence, shuffled using the given generator as a source for randomness.

func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator: (Self.Element) -> Bool) -> [ArraySlice<Self.Element>]

Returns the longest possible subsequences of the sequence, in order, that don’t contain elements satisfying the given predicate. Elements that are used to split the sequence are not returned as part of any subsequence.

func split(separator: Self.Element, maxSplits: Int, omittingEmptySubsequences: Bool) -> [ArraySlice<Self.Element>]

Returns the longest possible subsequences of the sequence, in order, around elements equal to the given element.

func starts<PossiblePrefix>(with: PossiblePrefix, by: (Self.Element, PossiblePrefix.Element) -> Bool) -> Bool

Returns a Boolean value indicating whether the initial elements of the sequence are equivalent to the elements in another sequence, using the given predicate as the equivalence test.

func suffix(Int) -> [Self.Element]

Returns a subsequence, up to the given maximum length, containing the final elements of the sequence.

func withContiguousStorageIfAvailable<R>((UnsafeBufferPointer<Self.Element>) -> R) -> R?

Call body(p), where p is a pointer to the collection’s contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of contiguous storage, body is not called and nil is returned.

Required. Default implementation provided.

Relationships

See Also

First Steps

protocol Collection

A sequence whose elements can be traversed multiple times, nondestructively, and accessed by an indexed subscript.