Async Sequences
An async sequence is like a regular list you loop through, except each item might take a little time to arrive, one at a time.
Iterating an Async Sequence with for await
An AsyncSequence's elements are consumed with for await, which suspends between each element as it becomes available.
Example: Iterating an Async Sequence with for await
struct Countdown: AsyncSequence {
typealias Element = Int
let start: Int
struct AsyncIterator: AsyncIteratorProtocol {
var current: Int
mutating func next() async -> Int? {
guard current > 0 else { return nil }
defer { current -= 1 }
return current
}
}
func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(current: start)
}
}
for await number in Countdown(start: 3) {
print(number)
}
Login to try C/C++/Java/PHP code in the editor
Collecting Async Sequence Results
Values produced by an async sequence can be collected into a regular array by appending each element inside a for await loop.
Example: Collecting Async Sequence Results
struct Countdown: AsyncSequence {
typealias Element = Int
let start: Int
struct AsyncIterator: AsyncIteratorProtocol {
var current: Int
mutating func next() async -> Int? {
guard current > 0 else { return nil }
defer { current -= 1 }
return current
}
}
func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(current: start)
}
}
var collected: [Int] = []
for await number in Countdown(start: 4) {
collected.append(number)
}
print(collected)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Trying to iterate an
AsyncSequencewith a plainfor-inloop; it requiresfor awaitinstead. - Forgetting a custom async sequence needs to implement
AsyncIteratorProtocol'snext()method as anasyncfunction. - Assuming an async sequence delivers all its values instantly; each element may genuinely be produced with a delay between them.
Chapter Summary
AsyncSequencedescribes a sequence whose elements are produced asynchronously, one at a time.- Iterating one requires
for await element in sequence. - A custom async sequence implements
AsyncIteratorProtocolwith anasync func next(). - Async sequences are useful for streams of data that arrive incrementally, like live updates.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: