Bird
Raised Fist0
Swiftprogramming~10 mins

Async sequences (AsyncSequence) in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Async sequences (AsyncSequence)
Start AsyncSequence
↓
Call async iterator
↓
Wait for next element asynchronously
↓
Receive element or nil
↓
Process element
↓
Repeat wait for next element
This flow shows how an async sequence produces elements one by one, waiting asynchronously for each before continuing or ending.
Execution Sample
Swift
struct Counter: AsyncSequence {
  typealias Element = Int
  struct AsyncIterator: AsyncIteratorProtocol {
    var count = 0
    mutating func next() async -> Int? {
      guard count < 3 else { return nil }
      defer { count += 1 }
      return count
    }
  }
  func makeAsyncIterator() -> AsyncIterator { AsyncIterator() }
}

let counter = Counter()
for await num in counter {
  print(num)
}
This code defines an async sequence that counts from 0 to 2 asynchronously, printing each number.
Execution Table
StepActioncount valuenext() returnsOutput
1Call next(), count=0 < 300Print 0
2Call next(), count=1 < 311Print 1
3Call next(), count=2 < 322Print 2
4Call next(), count=3 !< 33nilEnd loop
💡 next() returns nil when count reaches 3, ending the async sequence.
Variable Tracker
VariableStartAfter 1After 2After 3Final
count01233
Key Moments - 3 Insights
Why does next() return nil at step 4?
Because the count reached 3, which fails the guard condition count < 3, so next() returns nil to signal the end of the sequence (see execution_table step 4).
Why is count incremented after returning the value?
The defer statement increments count after returning the current value, so the returned number is the old count before increment (see execution_table steps 1-3).
How does the for-await loop know when to stop?
It stops when next() returns nil, which means no more elements are available (see execution_table step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of count when next() returns 1?
A0
B1
C2
D3
💡 Hint
Check execution_table row 2 under 'count value' and 'next() returns'.
At which step does the async sequence end?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Look for when next() returns nil in execution_table.
If we change the guard to count < 5, how many times will next() return a number?
A5 times
B4 times
C3 times
D6 times
💡 Hint
The sequence returns numbers while count < 5, so count values 0 to 4 (see variable_tracker).
Concept Snapshot
AsyncSequence lets you produce values asynchronously one by one.
Implement next() async -> Element? to yield values or nil to end.
Use for await to loop over async sequences.
next() suspends until the next value is ready.
Defer can update state after returning a value.
Full Transcript
This visual execution trace shows how an AsyncSequence in Swift works step-by-step. The Counter struct produces numbers 0, 1, and 2 asynchronously. Each call to next() checks if count is less than 3. If yes, it returns the current count and then increments it. When count reaches 3, next() returns nil, signaling the end of the sequence. The for-await loop prints each number as it arrives and stops when nil is returned. The variable tracker shows how count changes after each next() call. Key moments clarify why next() returns nil and how defer affects count. The quiz tests understanding of count values, sequence end, and changing the guard condition.

Practice

(1/5)
1. What is the main purpose of using AsyncSequence in Swift?
easy
A. To create synchronous loops that block until completion
B. To define static arrays with fixed values
C. To handle streams of values that arrive over time without blocking the program
D. To perform immediate calculations without delay

Solution

  1. Step 1: Understand AsyncSequence purpose

    AsyncSequence is designed to handle values that come asynchronously over time, like events or data streams.
  2. Step 2: Compare options with AsyncSequence use

    Only To handle streams of values that arrive over time without blocking the program correctly describes handling streams without blocking, which is the key feature of AsyncSequence.
  3. Final Answer:

    To handle streams of values that arrive over time without blocking the program -> Option C
  4. Quick Check:

    AsyncSequence = handle async streams [OK]
Hint: AsyncSequence handles values arriving over time without blocking [OK]
Common Mistakes:
  • Confusing AsyncSequence with synchronous loops
  • Thinking AsyncSequence is for static data
  • Assuming it blocks program execution
2. Which of the following is the correct syntax to iterate over an AsyncSequence named numbers?
easy
A. for await number in numbers { print(number) }
B. for number in numbers { print(number) }
C. while let number = numbers.next() { print(number) }
D. numbers.forEach { print($0) }

Solution

  1. Step 1: Recall AsyncSequence iteration syntax

    AsyncSequence requires asynchronous iteration using for await to wait for values.
  2. Step 2: Check each option

    for await number in numbers { print(number) } uses for await, which is correct. for number in numbers { print(number) } is synchronous, C is invalid syntax for AsyncSequence, and D is not supported.
  3. Final Answer:

    for await number in numbers { print(number) } -> Option A
  4. Quick Check:

    AsyncSequence loops use for await [OK]
Hint: Use 'for await' to loop over AsyncSequence values [OK]
Common Mistakes:
  • Using regular for loop without await
  • Trying to call next() synchronously
  • Using forEach which is not async-compatible
3. What will be printed by the following Swift code?
struct Counter: AsyncSequence {
  typealias Element = Int
  struct AsyncIterator: AsyncIteratorProtocol {
    var count = 1
    mutating func next() async -> Int? {
      guard count <= 3 else { return nil }
      defer { count += 1 }
      return count
    }
  }
  func makeAsyncIterator() -> AsyncIterator {
    AsyncIterator()
  }
}

let counter = Counter()
Task {
  for await number in counter {
    print(number)
  }
}
medium
A. 1 2 3
B. 0 1 2
C. 1 2 3 4
D. No output, code will not compile

Solution

  1. Step 1: Analyze AsyncIterator next() method

    The iterator returns count starting at 1, increments after returning, and stops after 3.
  2. Step 2: Trace iteration values

    Values returned are 1, then 2, then 3, then nil to end the loop.
  3. Final Answer:

    1 2 3 -> Option A
  4. Quick Check:

    AsyncSequence yields 1,2,3 then ends [OK]
Hint: Check next() return and guard condition carefully [OK]
Common Mistakes:
  • Assuming count starts at 0
  • Forgetting defer increments count after return
  • Expecting 4 as output
4. Identify the error in this AsyncSequence implementation:
struct SimpleAsync: AsyncSequence {
  typealias Element = String
  struct AsyncIterator: AsyncIteratorProtocol {
    func next() async -> String? {
      return "Hello"
    }
  }
  func makeAsyncIterator() -> AsyncIterator {
    AsyncIterator()
  }
}
medium
A. makeAsyncIterator() must be async
B. next() should be mutating to update state
C. AsyncIterator must be a class, not a struct
D. Element type cannot be String

Solution

  1. Step 1: Understand AsyncIteratorProtocol requirements

    The next() method often needs to update internal state, so it must be marked mutating in a struct.
  2. Step 2: Check the code's next() method

    Here, next() is not mutating but returns a constant string repeatedly, which is incorrect for iteration.
  3. Final Answer:

    next() should be mutating to update state -> Option B
  4. Quick Check:

    next() mutating required in struct iterator [OK]
Hint: next() in struct iterator must be mutating if state changes [OK]
Common Mistakes:
  • Thinking AsyncIterator must be a class
  • Making makeAsyncIterator async unnecessarily
  • Believing String cannot be Element type
5. You want to create an AsyncSequence that emits only even numbers from 2 to 10 inclusive. Which implementation correctly achieves this?
hard
A. struct EvenNumbers: AsyncSequence { typealias Element = Int struct AsyncIterator: AsyncIteratorProtocol { var current = 2 mutating func next() async -> Int? { guard current < 10 else { return nil } defer { current += 2 } return current } } func makeAsyncIterator() -> AsyncIterator { AsyncIterator() } }
B. struct EvenNumbers: AsyncSequence { typealias Element = Int struct AsyncIterator: AsyncIteratorProtocol { var current = 1 mutating func next() async -> Int? { guard current <= 10 else { return nil } defer { current += 1 } return current * 2 } } func makeAsyncIterator() -> AsyncIterator { AsyncIterator() } }
C. struct EvenNumbers: AsyncSequence { typealias Element = Int struct AsyncIterator: AsyncIteratorProtocol { var current = 0 mutating func next() async -> Int? { guard current <= 10 else { return nil } current += 2 return current } } func makeAsyncIterator() -> AsyncIterator { AsyncIterator() } }
D. struct EvenNumbers: AsyncSequence { typealias Element = Int struct AsyncIterator: AsyncIteratorProtocol { var current = 2 mutating func next() async -> Int? { if current > 10 { return nil } let result = current current += 2 return result } } func makeAsyncIterator() -> AsyncIterator { AsyncIterator() } }

Solution

  1. Step 1: Identify required sequence

    Even numbers from 2 to 10 inclusive: 2, 4, 6, 8, 10 exactly.
  2. Step 2: Trace execution of each

    A (< 10, defer +=2): 2,4,6,8 (stops at current=10). Misses 10.
    B (*2 on odds): 2,4,6,8,10,12,... overshoots.
    C (<=10, +=2 first): 2,4,6,8,10,12 extra.
    D (if >10 nil, result first): 2,4,6,8,10 perfect.
  3. Final Answer:

    if current > 10 { return nil }
    let result = current
    current += 2
    return result
    -> Option D
  4. Quick Check:

    Only D emits exactly 2,4,6,8,10 [OK]
Hint: Return current before increment; stop when current > 10 [OK]
Common Mistakes:
  • Incrementing before returning causing off-by-one errors
  • Incorrect guard conditions excluding last value
  • Multiplying inside next() causing wrong sequence
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard