Protocolswift 6.0.1Swift
Sequence
A type that provides sequential, iterated access to its elements.
protocol Sequence<Element>
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
associatedtype Element
A type representing the sequence’s elements.
associatedtype Iterator
A type that provides the sequence’s iteration interface and encapsulates its iteration state.
Instance members
var underestimatedCount: Int
A value less than or equal to the number of elements in the sequence, calculated nondestructively.
func makeIterator(
) -> Self.Iterator Returns an iterator over the elements of this sequence.
func withContiguousStorageIfAvailable<R>((UnsafeBufferPointer<Self.Element>) throws -> R
) rethrows -> R? Executes a closure on the sequence’s contiguous storage.
Citizens in Swift
Instance members
var lazy: LazySequence<Self>
A sequence containing the same elements as this sequence, but on which some operations, such as
map
andfilter
, are implemented lazily.var underestimatedCount: Int
A value less than or equal to the number of elements in the sequence, calculated nondestructively.
func allSatisfy((Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.
func compactMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] Returns an array containing the non-
nil
results of calling the given transformation with each element of this sequence.func contains(where: (Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
func count<E>(where: (Self.Element)
throws Returns the number of elements in the sequence that satisfy the given predicate.
func drop(while: (Self.Element) throws -> Bool
) rethrows -> 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 elementsEqual<OtherSequence>(OtherSequence, by: (Self.Element, OtherSequence.Element) throws -> Bool
) rethrows -> 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 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.
func filter((Self.Element) throws -> Bool
) rethrows -> [Self.Element] Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
func first(where: (Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the first element of the sequence that satisfies the given predicate.
func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.
func forEach((Self.Element) throws -> Void
) rethrows Calls the given closure on each element in the sequence in the same order as a
for
-in
loop.func lexicographicallyPrecedes<OtherSequence>(OtherSequence, by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.
func map<T, E>((Self.Element)
throws Returns an array containing the results of mapping the given closure over the sequence’s elements.
func max(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
func min(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the minimum element in the sequence, using the given predicate as the comparison between 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) throws -> Bool
) rethrows -> [Self.Element] Returns a sequence containing the initial, consecutive elements that satisfy the given predicate.
func reduce<Result>(Result, (Result, Self.Element) throws -> Result
) rethrows -> Result Returns the result of combining the elements of the sequence using the given closure.
func reduce<Result>(into: Result, (inout Result, Self.Element) throws -> ()
) rethrows -> Result Returns the result of combining the elements of the sequence using the given closure.
func reversed(
) -> [Self.Element] Returns an array containing the elements of this sequence in reverse order.
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 sorted(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> [Self.Element] Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.
func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator: (Self.Element) throws -> Bool
) rethrows -> [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 starts<PossiblePrefix>(with: PossiblePrefix, by: (Self.Element, PossiblePrefix.Element) throws -> Bool
) rethrows -> 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>) throws -> R
) rethrows -> R?
Show obsolete interfaces (1)
Hide obsolete interfaces
Subtypes
protocol BidirectionalCollection<Element>
A collection that supports backward as well as forward traversal.
protocol Collection<Element>
A sequence whose elements can be traversed multiple times, nondestructively, and accessed by an indexed subscript.
protocol LazyCollectionProtocol
protocol LazySequenceProtocol
A sequence on which normally-eager sequence operations are implemented lazily.
protocol MutableCollection<Element>
A collection that supports subscript assignment.
protocol RandomAccessCollection<Element>
A collection that supports efficient random-access index traversal.
protocol RangeReplaceableCollection<Element>
A collection that supports replacement of an arbitrary subrange of elements with the elements of another collection.
protocol StringProtocol
A type that can represent a string as a collection of characters.
Citizens in Swift
where Self == Self.Iterator
Instance members
func makeIterator(
) -> Self Returns an iterator over the elements of this sequence.
Citizens in Swift
where Self.Element:Comparable
Instance members
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 max(
) -> Self.Element? Returns the maximum element in the sequence.
func min(
) -> Self.Element? Returns the minimum element in the sequence.
func sorted(
) -> [Self.Element] Returns the elements of the sequence, sorted.
Citizens in Swift
where Self.Element:Equatable
Instance members
func contains(Self.Element
) -> Bool Returns a Boolean value indicating whether the sequence contains the given element.
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 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
) -> Bool Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.
Citizens in Swift
where Self.Element:Sequence
Instance members
func joined(
) -> FlattenSequence<Self> Returns the elements of this sequence of sequences, concatenated.
func joined<Separator>(separator: Separator
) -> JoinedSequence<Self> Returns the concatenated elements of this sequence of sequences, inserting the given separator between each element.
Citizens in Swift
where Self.Element:StringProtocol
Instance members
func joined(separator: String
) -> String Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.
Available in _RegexParser
Instance members
Available in Cxx
Subtypes
protocol CxxRandomAccessCollection<Element>
protocol CxxSequence<Element>
Use this protocol to conform custom C++ sequence types to Swift’s
Sequence
protocol like this:
Available in FoundationEssentials
Instance members
func compare<Comparator>(Comparator.Compared, Comparator.Compared
) -> ComparisonResult If
lhs
is ordered beforerhs
in the ordering described by the given sequence ofSortComparator
sfunc filter(Predicate<Self.Element>
) throws -> [Self.Element] func sorted<Comparator>(using: Comparator
) -> [Self.Element] Returns the elements of the sequence, sorted using the given comparator to compare elements.
func sorted<S, Comparator>(using: S
) -> [Self.Element] Returns the elements of the sequence, sorted using the given array of
SortComparator
s to compare elements.
Subtypes
Available in FoundationInternationalization
Instance members
Available in FoundationInternationalization
where Self.Element == String
Instance members
Extension in Algorithms
Instance members
func adjacentPairs(
) -> AdjacentPairsSequence<Self> Returns a sequence of overlapping adjacent pairs of the elements of this sequence.
func compacted<Unwrapped>(
) -> CompactedSequence<Self, Unwrapped> Returns a new
Sequence
that iterates over every non-nil element from the originalSequence
.func firstNonNil<Result>((Element) throws -> Result?
) rethrows -> Result? Returns the first non-
nil
result obtained from applying the given transformation to the elements of the sequence.func grouped<GroupKey>(by: (Element) throws -> GroupKey
) rethrows -> [GroupKey : [Element]] Groups up elements of
self
into a new Dictionary, whose values are Arrays of grouped elements, each keyed by the group key returned by the given closure.func interspersed(with: Element
) -> InterspersedSequence<Self> Returns a sequence containing elements of this sequence with the given separator inserted in between each element.
func keyed<Key>(by: (Element) throws -> Key
) rethrows -> [Key : Element] Creates a new Dictionary from the elements of
self
, keyed by the results returned by the givenkeyForValue
closure.func keyed<Key>(by: (Element) throws -> Key, resolvingConflictsWith: (Key, Element, Element) throws -> Element
) rethrows -> [Key : Element] Creates a new Dictionary from the elements of
self
, keyed by the results returned by the givenkeyForValue
closure. As the dictionary is built, the initializer calls theresolve
closure with the current and new values for any duplicate keys. Pass a closure asresolve
that returns the value to use in the resulting dictionary: The closure can choose between the two values, combine them to produce a new value, or even throw an error.func max(count: Int, sortedBy: (Element, Element) throws -> Bool
) rethrows -> [Element] Returns the largest elements of this sequence, as sorted by the given predicate.
func min(count: Int, sortedBy: (Element, Element) throws -> Bool
) rethrows -> [Element] Returns the smallest elements of this sequence, as sorted by the given predicate.
func minAndMax(by: (Element, Element) throws -> Bool
) rethrows -> (min: Element, max: Element)? Returns both the minimum and maximum elements in the sequence, using the given predicate as the comparison between elements.
func partitioned(by: (Element) throws -> Bool
) rethrows -> (falseElements: [Element], trueElements: [Element]) Returns two arrays containing, in order, the elements of the sequence that do and don’t satisfy the given predicate.
func randomSample(count: Int
) -> [Element] Randomly selects the specified number of elements from this sequence.
func randomSample<G>(count: Int, using: inout G
) -> [Element] Randomly selects the specified number of elements from this sequence.
func reductions((Element, Element) throws -> Element
) rethrows -> [Element] Returns an array containing the accumulated results of combining the elements of the sequence using the given closure.
func reductions<Result>(Result, (Result, Element) throws -> Result
) rethrows -> [Result] Returns an array containing the accumulated results of combining the elements of the sequence using the given closure.
func reductions<Result>(into: Result, (inout Result, Element) throws -> Void
) rethrows -> [Result] Returns an array containing the accumulated results of combining the elements of the sequence using the given closure.
func striding(by: Int
) -> StridingSequence<Self> Returns a sequence stepping through the elements every
step
starting at the first value. Any remainders of the stride will be trimmed.func uniqued<Subject>(on: (Element) throws -> Subject
) rethrows -> [Element] Returns an array with the unique elements of this sequence (as determined by the given projection), in the order of the first occurrence of each unique element.
Extension in Algorithms
where Self.Element:Hashable
Instance members
func uniqued(
) -> UniquedSequence<Self, Element> Returns a sequence with only the unique elements of this sequence, in the order of the first occurrence of each unique element.
Extension in Algorithms
where Self.Element:Comparable
Instance members
func max(count: Int
) -> [Element] Returns the largest elements of this sequence.
func min(count: Int
) -> [Element] Returns the smallest elements of this sequence.
func minAndMax(
) -> (min: Element, max: Element)? Returns both the minimum and maximum elements in the sequence.
Extension in Algorithms
where Self.Element:Sequence
Instance members
func joined<Separator>(by: Separator
) -> JoinedBySequence<Self, Separator> Returns the concatenation of the elements in this sequence of sequences, inserting the given separator between each sequence.
func joined(by: Element.Element
) -> JoinedBySequence<Self, CollectionOfOne<Element.Element>> Returns the concatenation of the elements in this sequence of sequences, inserting the given separator between each sequence.
func joined<Separator>(by: (Element, Element) throws -> Separator
) rethrows -> [Element.Element] Returns the concatenation of the elements in this sequence of sequences, inserting the separator produced by the closure between each sequence.
func joined(by: (Element, Element) throws -> Element.Element
) rethrows -> [Element.Element] Returns the concatenation of the elements in this sequence of sequences, inserting the separator produced by the closure between each sequence.
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
andfilter
, are implemented asynchronously.
Extension in Crypto
Subtypes
protocol Digest
A type that represents the output of a hash.
protocol MessageAuthenticationCode
A type that represents a message authentication code.
Extension in _NIOFileSystem
Instance members
func write(toFileAt: FilePath, absoluteOffset: Int64, options: OpenOptions.Write
) async throws -> Int64 Writes the contents of the
Sequence
to a file.func write(toFileAt: FilePath, absoluteOffset: Int64, options: OpenOptions.Write, fileSystem: some FileSystemProtocol
) async throws -> Int64 Writes the contents of the
Sequence
to a file.
Extension in PackageModel
where Self.Element == Module
Instance members
Extension in Vapor
where Self.Element == UInt8