← Back to Swift Course | Chapter 13: Concurrency | Lesson 6 of 6

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

markup
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)
}

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

markup
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)
Common Mistakes
  1. Trying to iterate an AsyncSequence with a plain for-in loop; it requires for await instead.
  2. Forgetting a custom async sequence needs to implement AsyncIteratorProtocol's next() method as an async function.
  3. Assuming an async sequence delivers all its values instantly; each element may genuinely be produced with a delay between them.
Chapter Summary
  • AsyncSequence describes a sequence whose elements are produced asynchronously, one at a time.
  • Iterating one requires for await element in sequence.
  • A custom async sequence implements AsyncIteratorProtocol with an async 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.