Async sequences (AsyncSequence) in Swift - Time & Space Complexity
When working with async sequences, it's important to understand how the time to process elements grows as the sequence gets longer.
We want to know how the number of steps changes when we read more items asynchronously.
Analyze the time complexity of the following code snippet.
func printNumbers(n: Int) async {
for await number in AsyncStream { cont in
for i in 1...n {
cont.yield(i)
}
cont.finish()
} {
print(number)
}
}
This code asynchronously prints numbers from 1 to n using an async sequence.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The asynchronous loop that waits for and processes each number in the sequence.
- How many times: It runs once for each number from 1 to n, so n times.
As the number of items n increases, the total steps increase roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 async steps |
| 100 | About 100 async steps |
| 1000 | About 1000 async steps |
Pattern observation: The time grows steadily as you add more items, roughly one step per item.
Time Complexity: O(n)
This means the time to process the async sequence grows linearly with the number of items.
[X] Wrong: "Async sequences run all items at once, so time doesn't grow with n."
[OK] Correct: Async sequences produce items one by one, so processing time adds up with each item.
Understanding async sequences' time behavior shows you can reason about asynchronous code performance, a key skill in modern Swift development.
"What if we changed the async sequence to produce items in parallel? How would the time complexity change?"
Practice
AsyncSequence in Swift?Solution
Step 1: Understand AsyncSequence purpose
AsyncSequence is designed to handle values that come asynchronously over time, like events or data streams.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.Final Answer:
To handle streams of values that arrive over time without blocking the program -> Option CQuick Check:
AsyncSequence = handle async streams [OK]
- Confusing AsyncSequence with synchronous loops
- Thinking AsyncSequence is for static data
- Assuming it blocks program execution
AsyncSequence named numbers?Solution
Step 1: Recall AsyncSequence iteration syntax
AsyncSequence requires asynchronous iteration usingfor awaitto wait for values.Step 2: Check each option
for await number in numbers { print(number) } usesfor await, which is correct. for number in numbers { print(number) } is synchronous, C is invalid syntax for AsyncSequence, and D is not supported.Final Answer:
for await number in numbers { print(number) } -> Option AQuick Check:
AsyncSequence loops use for await [OK]
- Using regular for loop without await
- Trying to call next() synchronously
- Using forEach which is not async-compatible
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)
}
}Solution
Step 1: Analyze AsyncIterator next() method
The iterator returns count starting at 1, increments after returning, and stops after 3.Step 2: Trace iteration values
Values returned are 1, then 2, then 3, then nil to end the loop.Final Answer:
1 2 3 -> Option AQuick Check:
AsyncSequence yields 1,2,3 then ends [OK]
- Assuming count starts at 0
- Forgetting defer increments count after return
- Expecting 4 as output
struct SimpleAsync: AsyncSequence {
typealias Element = String
struct AsyncIterator: AsyncIteratorProtocol {
func next() async -> String? {
return "Hello"
}
}
func makeAsyncIterator() -> AsyncIterator {
AsyncIterator()
}
}Solution
Step 1: Understand AsyncIteratorProtocol requirements
The next() method often needs to update internal state, so it must be marked mutating in a struct.Step 2: Check the code's next() method
Here, next() is not mutating but returns a constant string repeatedly, which is incorrect for iteration.Final Answer:
next() should be mutating to update state -> Option BQuick Check:
next() mutating required in struct iterator [OK]
- Thinking AsyncIterator must be a class
- Making makeAsyncIterator async unnecessarily
- Believing String cannot be Element type
Solution
Step 1: Identify required sequence
Even numbers from 2 to 10 inclusive: 2, 4, 6, 8, 10 exactly.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.Final Answer:
if current > 10 { return nil }
let result = current
current += 2
return result -> Option DQuick Check:
Only D emits exactly 2,4,6,8,10 [OK]
- Incrementing before returning causing off-by-one errors
- Incorrect guard conditions excluding last value
- Multiplying inside next() causing wrong sequence
Ready to prove it?
Pass the test and this pattern moves unknown
