Protocol_Concurrency5.9.0
AsyncSequence
A type that provides asynchronous, sequential, iterated access to its elements.
- iOS
- 13.0+
- macOS
- 10.15+
- tvOS
- 13.0+
- watchOS
- 6.0+
@rethrows protocol AsyncSequence
An AsyncSequence
resembles the Sequence
type — offering a list of values you can step through one at a time — and adds asynchronicity. An AsyncSequence
may have all, some, or none of its values available when you first use it. Instead, you use await
to receive values as they become available.
As with Sequence
, you typically iterate through an AsyncSequence
with a for await
-in
loop. However, because the caller must potentially wait for values, you use the await
keyword. The following example shows how to iterate over Counter
, a custom AsyncSequence
that produces Int
values from 1
up to a howHigh
value:
for await number in Counter(howHigh: 10) {
print(number, terminator: " ")
}
// Prints "1 2 3 4 5 6 7 8 9 10 "
An AsyncSequence
doesn’t generate or contain the values; it just defines how you access them. Along with defining the type of values as an associated type called Element
, the AsyncSequence
defines a makeAsyncIterator()
method. This returns an instance of type AsyncIterator
. Like the standard IteratorProtocol
, the AsyncIteratorProtocol
defines a single next()
method to produce elements. The difference is that the AsyncIterator
defines its next()
method as async
, which requires a caller to wait for the next value with the await
keyword.
AsyncSequence
also defines methods for processing the elements you receive, modeled on the operations provided by the basic Sequence
in the standard library. There are two categories of methods: those that return a single value, and those that return another AsyncSequence
.
Single-value methods eliminate the need for a for await
-in
loop, and instead let you make a single await
call. For example, the contains(_:)
method returns a Boolean value that indicates if a given value exists in the AsyncSequence
. Given the Counter
sequence from the previous example, you can test for the existence of a sequence member with a one-line call:
let found = await Counter(howHigh: 10).contains(5) // true
Methods that return another AsyncSequence
return a type specific to the method’s semantics. For example, the .map(_:)
method returns a AsyncMapSequence
(or a AsyncThrowingMapSequence
, if the closure you provide to the map(_:)
method can throw an error). These returned sequences don’t eagerly await the next member of the sequence, which allows the caller to decide when to start work. Typically, you’ll iterate over these sequences with for await
-in
, like the base AsyncSequence
you started with. In the following example, the map(_:)
method transforms each Int
received from a Counter
sequence into a String
:
let stream = Counter(howHigh: 10)
.map { $0 % 2 == 0 ? "Even" : "Odd" }
for await s in stream {
print(s, terminator: " ")
}
// Prints "Odd Even Odd Even Odd Even Odd Even Odd Even "
Requirements
associatedtype AsyncIterator : AsyncIteratorProtocol
The type of asynchronous iterator that produces elements of this asynchronous sequence.
associatedtype Element
The type of element produced by this asynchronous sequence.
func makeAsyncIterator(
) -> Self.AsyncIterator Creates the asynchronous iterator that produces elements of this asynchronous sequence.
Citizens in _Concurrency
Members
func allSatisfy((Self.Element) async throws -> Bool
) async rethrows -> Bool Returns a Boolean value that indicates whether all elements produced by the asynchronous sequence satisfy the given predicate.
func compactMap<ElementOfResult>((Self.Element) async -> ElementOfResult?
) -> AsyncCompactMapSequence<Self, ElementOfResult> Creates an asynchronous sequence that maps the given closure over the asynchronous sequence’s elements, omitting results that don’t return a value.
func compactMap<ElementOfResult>((Self.Element) async throws -> ElementOfResult?
) -> AsyncThrowingCompactMapSequence<Self, ElementOfResult> Creates an asynchronous sequence that maps an error-throwing closure over the base sequence’s elements, omitting results that don’t return a value.
func contains(where: (Self.Element) async throws -> Bool
) async rethrows -> Bool Returns a Boolean value that indicates whether the asynchronous sequence contains an element that satisfies the given predicate.
func drop(while: (Self.Element) async -> Bool
) -> AsyncDropWhileSequence<Self> Omits elements from the base asynchronous sequence until a given closure returns false, after which it passes through all remaining elements.
func drop(while: (Self.Element) async throws -> Bool
) -> AsyncThrowingDropWhileSequence<Self> Omits elements from the base sequence until a given error-throwing closure returns false, after which it passes through all remaining elements.
func dropFirst(Int
) -> AsyncDropFirstSequence<Self> Omits a specified number of elements from the base asynchronous sequence, then passes through all remaining elements.
func filter((Self.Element) async -> Bool
) -> AsyncFilterSequence<Self> Creates an asynchronous sequence that contains, in order, the elements of the base sequence that satisfy the given predicate.
func filter((Self.Element) async throws -> Bool
) -> AsyncThrowingFilterSequence<Self> Creates an asynchronous sequence that contains, in order, the elements of the base sequence that satisfy the given error-throwing predicate.
func first(where: (Self.Element) async throws -> Bool
) async rethrows -> Self.Element? Returns the first element of the sequence that satisfies the given predicate.
func flatMap<SegmentOfResult>((Self.Element) async throws -> SegmentOfResult
) -> AsyncThrowingFlatMapSequence<Self, SegmentOfResult> Creates an asynchronous sequence that concatenates the results of calling the given error-throwing transformation with each element of this sequence.
func flatMap<SegmentOfResult>((Self.Element) async -> SegmentOfResult
) -> AsyncFlatMapSequence<Self, SegmentOfResult> Creates an asynchronous sequence that concatenates the results of calling the given transformation with each element of this sequence.
func map<Transformed>((Self.Element) async -> Transformed
) -> AsyncMapSequence<Self, Transformed> Creates an asynchronous sequence that maps the given closure over the asynchronous sequence’s elements.
func map<Transformed>((Self.Element) async throws -> Transformed
) -> AsyncThrowingMapSequence<Self, Transformed> Creates an asynchronous sequence that maps the given error-throwing closure over the asynchronous sequence’s elements.
func max(by: (Self.Element, Self.Element) async throws -> Bool
) async rethrows -> Self.Element? Returns the maximum element in the asynchronous sequence, using the given predicate as the comparison between elements.
func min(by: (Self.Element, Self.Element) async throws -> Bool
) async rethrows -> Self.Element? Returns the minimum element in the asynchronous sequence, using the given predicate as the comparison between elements.
func prefix(Int
) -> AsyncPrefixSequence<Self> Returns an asynchronous sequence, up to the specified maximum length, containing the initial elements of the base asynchronous sequence.
func prefix(while: (Self.Element) async -> Bool
) rethrows -> AsyncPrefixWhileSequence<Self> Returns an asynchronous sequence, containing the initial, consecutive elements of the base sequence that satisfy the given predicate.
func prefix(while: (Self.Element) async throws -> Bool
) rethrows -> AsyncThrowingPrefixWhileSequence<Self> Returns an asynchronous sequence, containing the initial, consecutive elements of the base sequence that satisfy the given error-throwing predicate.
func reduce<Result>(Result, (Result, Self.Element) async throws -> Result
) async rethrows -> Result Returns the result of combining the elements of the asynchronous sequence using the given closure.
func reduce<Result>(into: Result, (inout Result, Self.Element) async throws -> Void
) async rethrows -> Result Returns the result of combining the elements of the asynchronous sequence using the given closure, given a mutable initial value.
Citizens in _Concurrency
where Self.Element:Comparable
Members
func max(
) async rethrows -> Self.Element? Returns the maximum element in an asynchronous sequence of comparable elements.
func min(
) async rethrows -> Self.Element? Returns the minimum element in an asynchronous sequence of comparable elements.
Citizens in _Concurrency
where Self.Element:Equatable
Members
func contains(Self
.Element) async rethrows -> Bool Returns a Boolean value that indicates whether the asynchronous sequence contains the given element.
Extension in AsyncAlgorithms
Members
func adjacentPairs(
) -> AsyncAdjacentPairsSequence<Self> An
AsyncSequence
that iterates over the adjacent pairs of the original originalAsyncSequence
.func chunked(by: (Self.Element, Self.Element) -> Bool
) -> AsyncChunkedByGroupSequence<Self, [Self.Element]> Creates an asynchronous sequence that creates chunks by testing if elements belong in the same group.
func chunked<C>(by: AsyncTimerSequence<C>
) -> AsyncChunksOfCountOrSignalSequence<Self, [Self.Element], AsyncTimerSequence<C>> Creates an asynchronous sequence that creates chunks when an
AsyncTimerSequence
fires.func chunked<Signal>(by: Signal
) -> AsyncChunksOfCountOrSignalSequence<Self, [Self.Element], Signal> Creates an asynchronous sequence that creates chunks when a signal
AsyncSequence
produces an element.func chunked<C, Collected>(by: AsyncTimerSequence<C>, into: Collected.Type
) -> AsyncChunksOfCountOrSignalSequence<Self, Collected, AsyncTimerSequence<C>> Creates an asynchronous sequence that creates chunks of a given
RangeReplaceableCollection
type when anAsyncTimerSequence
fires.func chunked<Signal, Collected>(by: Signal, into: Collected.Type
) -> AsyncChunksOfCountOrSignalSequence<Self, Collected, Signal> Creates an asynchronous sequence that creates chunks of a given
RangeReplaceableCollection
type when a signalAsyncSequence
produces an element.func chunked<Collected>(into: Collected.Type, by: (Self.Element, Self.Element) -> Bool
) -> AsyncChunkedByGroupSequence<Self, Collected> Creates an asynchronous sequence that creates chunks of a given
RangeReplaceableCollection
type by testing if elements belong in the same group.func chunked<Subject, Collected>(into: Collected.Type, on: (Self.Element) -> Subject
) -> AsyncChunkedOnProjectionSequence<Self, Subject, Collected> Creates an asynchronous sequence that creates chunks of a given
RangeReplaceableCollection
type on the uniqueness of a given subject.func chunked<Subject>(on: (Self.Element) -> Subject
) -> AsyncChunkedOnProjectionSequence<Self, Subject, [Self.Element]> Creates an asynchronous sequence that creates chunks on the uniqueness of a given subject.
func chunks(ofCount: Int
) -> AsyncChunksOfCountSequence<Self, [Self.Element]> Creates an asynchronous sequence that creates chunks of a given count.
func chunks<Collected>(ofCount: Int, into: Collected.Type
) -> AsyncChunksOfCountSequence<Self, Collected> Creates an asynchronous sequence that creates chunks of a given
RangeReplaceableCollection
of a given count.func chunks<C>(ofCount: Int, or: AsyncTimerSequence<C>
) -> AsyncChunksOfCountOrSignalSequence<Self, [Self.Element], AsyncTimerSequence<C>> Creates an asynchronous sequence that creates chunks of a given count or when an
AsyncTimerSequence
fires.func chunks<Signal>(ofCount: Int, or: Signal
) -> AsyncChunksOfCountOrSignalSequence<Self, [Self.Element], Signal> Creates an asynchronous sequence that creates chunks of a given count or when a signal
AsyncSequence
produces an element.func chunks<C, Collected>(ofCount: Int, or: AsyncTimerSequence<C>, into: Collected.Type
) -> AsyncChunksOfCountOrSignalSequence<Self, Collected, AsyncTimerSequence<C>> Creates an asynchronous sequence that creates chunks of a given
RangeReplaceableCollection
type of a given count or when anAsyncTimerSequence
fires.func chunks<Signal, Collected>(ofCount: Int, or: Signal, into: Collected.Type
) -> AsyncChunksOfCountOrSignalSequence<Self, Collected, Signal> Creates an asynchronous sequence that creates chunks of a given
RangeReplaceableCollection
type of a given count or when a signalAsyncSequence
produces an element.func compacted<Unwrapped>(
) -> AsyncCompactedSequence<Self, Unwrapped> Returns a new
AsyncSequence
that iterates over every non-nil element from the originalAsyncSequence
.func debounce(for: Duration, tolerance: Duration?
) -> AsyncDebounceSequence<Self, ContinuousClock> Creates an asynchronous sequence that emits the latest element after a given quiescence period has elapsed.
func debounce<C>(for: C.Instant.Duration, tolerance: C.Instant.Duration?, clock: C
) -> AsyncDebounceSequence<Self, C> Creates an asynchronous sequence that emits the latest element after a given quiescence period has elapsed by using a specified Clock.
func interspersed(with: Self.Element
) -> AsyncInterspersedSequence<Self> Returns an asynchronous sequence containing elements of this asynchronous sequence with the given separator inserted in between each element.
func joined(
) -> AsyncJoinedSequence<Self> Concatenate an
AsyncSequence
ofAsyncSequence
elementsfunc joined<Separator>(separator: Separator
) -> AsyncJoinedBySeparatorSequence<Self, Separator> Concatenate an
AsyncSequence
ofAsyncSequence
elements with a separator.func reductions((Self.Element, Self.Element) async -> Self.Element
) -> AsyncInclusiveReductionsSequence<Self> Returns an asynchronous sequence containing the accumulated results of combining the elements of the asynchronous sequence using the given closure.
func reductions((Self.Element, Self.Element) async throws -> Self.Element
) -> AsyncThrowingInclusiveReductionsSequence<Self> Returns an asynchronous sequence containing the accumulated results of combining the elements of the asynchronous sequence using the given error-throwing closure.
func reductions<Result>(Result, (Result, Self.Element) async -> Result
) -> AsyncExclusiveReductionsSequence<Self, Result> Returns an asynchronous sequence containing the accumulated results of combining the elements of the asynchronous sequence using the given closure.
func reductions<Result>(Result, (Result, Self.Element) async throws -> Result
) -> AsyncThrowingExclusiveReductionsSequence<Self, Result> Returns an asynchronous sequence containing the accumulated results of combining the elements of the asynchronous sequence using the given error-throwing closure.
func reductions<Result>(into: Result, (inout Result, Self.Element) async -> Void
) -> AsyncExclusiveReductionsSequence<Self, Result> Returns an asynchronous sequence containing the accumulated results of combining the elements of the asynchronous sequence using the given closure.
func reductions<Result>(into: Result, (inout Result, Self.Element) async throws -> Void
) -> AsyncThrowingExclusiveReductionsSequence<Self, Result> Returns an asynchronous sequence containing the accumulated results of combining the elements of the asynchronous sequence using the given error-throwing closure.
func removeDuplicates(by: (Self.Element, Self.Element) async throws -> Bool
) -> AsyncThrowingRemoveDuplicatesSequence<Self> Creates an asynchronous sequence that omits repeated elements by testing them with an error-throwing predicate.
func removeDuplicates(by: (Self.Element, Self.Element) async -> Bool
) -> AsyncRemoveDuplicatesSequence<Self> Creates an asynchronous sequence that omits repeated elements by testing them with a predicate.
func throttle<C>(for: C.Instant.Duration, clock: C, latest: Bool
) -> AsyncThrottleSequence<Self, C, Self.Element> Create a rate-limited
AsyncSequence
by emitting values at most every specified interval.func throttle<C, Reduced>(for: C.Instant.Duration, clock: C, reducing: (Reduced?, Self.Element) async -> Reduced
) -> AsyncThrottleSequence<Self, C, Reduced> Create a rate-limited
AsyncSequence
by emitting values at most every specified interval.func throttle(for: Duration, latest: Bool
) -> AsyncThrottleSequence<Self, ContinuousClock, Self.Element> Create a rate-limited
AsyncSequence
by emitting values at most every specified interval.func throttle<Reduced>(for: Duration, reducing: (Reduced?, Self.Element) async -> Reduced
) -> AsyncThrottleSequence<Self, ContinuousClock, Reduced> Create a rate-limited
AsyncSequence
by emitting values at most every specified interval.
Extension in AsyncAlgorithms
where Self:Sendable
Members
func buffer(policy: AsyncBufferSequencePolicy
) -> AsyncBufferSequence<Self> Creates an asynchronous sequence that buffers elements.
Extension in AsyncAlgorithms
where Self.Element:Equatable
Members
func removeDuplicates(
) -> AsyncRemoveDuplicatesSequence<Self> Creates an asynchronous sequence that omits repeated elements.
Extension in NIOCore
where Self.Element:RandomAccessCollection, Self.Element.Element == UInt8
Members
func collect(upTo: Int, into: inout ByteBuffer
) async throws Accumulates an
Swift.AsyncSequence
ofSwift.RandomAccessCollection
s into a singleaccumulationBuffer
.func collect(upTo: Int, using: ByteBufferAllocator
) async throws -> ByteBuffer Accumulates an
Swift.AsyncSequence
ofSwift.RandomAccessCollection
s into a singleByteBuffer
.
Extension in NIOCore
where Self.Element == ByteBuffer
Members
func collect(upTo: Int
) async throws -> ByteBuffer Accumulates an
AsyncSequence
ofByteBuffer
s into a singleByteBuffer
.func collect(upTo: Int, into: inout ByteBuffer
) async throws Accumulates an
AsyncSequence
ofByteBuffer
s into a singleaccumulationBuffer
.