Predict the output
What does this print?
func ticks(_ count: Int) -> AsyncStream<Int> {
AsyncStream { continuation in
Task {
for i in 1...count {
try? await Task.sleep(for: .milliseconds(100))
continuation.yield(i)
}
}
}
}
for await t in ticks(3) { print(t) }
print("finished")Hint 1 of 1
When does a for-await loop end?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B 1, 2, 3, then the loop waits forever and 'finished' never prints
Correct. Add continuation.finish() after the loop.
Why not the others?
- A 1, 2, 3, finished. The loop ends only when the stream finishes, and nothing calls
finish(). - C Nothing, because the stream never starts. The build closure runs immediately and the Task starts yielding.
- D It doesn't compile until you call
finish(throwing:). Plain AsyncStream has onlyfinish();finish(throwing:)belongs to AsyncThrowingStream.