Complete the code to declare an async sequence using AsyncStream.
let numbers = AsyncStream<Int> { continuation in
continuation.yield(1)
continuation.yield(2)
continuation.finish()
}
Task: Use a for await loop to iterate over [1].Array with for await (Array is not async sequence).DispatchQueue or Task instead of the async sequence variable.The variable numbers is the async sequence created with AsyncStream. You use for await to iterate over it.
Complete the async function to return an AsyncStream of integers from 1 to 3.
func makeNumbers() -> AsyncStream<Int> {
AsyncStream { continuation in
for i in 1...3 {
continuation.[1](i)
}
continuation.finish()
}
}send, emit, or push which are not valid methods for AsyncStream.The method to send values to an AsyncStream is yield.
Fix the error in the async sequence iteration by completing the missing keyword.
func printNumbers() async {
let stream = AsyncStream<Int> { continuation in
continuation.yield(10)
continuation.finish()
}
for [1] number in stream {
print(number)
}
}for async or just for which causes errors.When iterating over an async sequence, you must use for await to wait for each value asynchronously.
Fill both blanks to create an AsyncStream that yields strings and finishes properly.
let greetings = AsyncStream<String> { [1] in
[2].yield("Hello")
[2].finish()
}The closure parameter is usually named continuation. You call yield and finish on it.
Fill all three blanks to create a filtered async sequence of integers greater than 5.
let filtered = AsyncStream<Int> { continuation in
for i in 1...10 {
if i [1] 5 {
continuation.[2](i)
}
}
continuation.[3]()
}The condition checks if i > 5. Then yield sends the value, and finish ends the stream.