Complete the code to declare an asynchronous sequence using AsyncSequence protocol.
struct NumberIterator: AsyncIteratorProtocol {
typealias Element = Int
var current = 1
mutating func next() async -> [1] {
guard current <= 3 else { return nil }
defer { current += 1 }
return current
}
}
struct NumberSequence: AsyncSequence {
typealias Element = Int
func makeAsyncIterator() -> NumberIterator {
return NumberIterator()
}
}The next() method of AsyncIteratorProtocol must return an optional element (Element?) asynchronously. Here, since Element is Int, the return type is Int?.
Complete the code to asynchronously iterate over the NumberSequence and print each number.
let sequence = NumberSequence()
Task {
var iterator = sequence.makeAsyncIterator()
while let number = await [1] {
print(number)
}
}To get the next element asynchronously, call await iterator.next(). This returns the next optional element from the iterator.
Fix the error in the async for loop to iterate over the sequence correctly.
let sequence = NumberSequence()
Task {
for await [1] in sequence {
print([1])
}
}The variable name inside the loop can be any valid identifier. Here, number is a clear and descriptive name for each element in the sequence.
Fill both blanks to create a filtered async sequence that yields only even numbers.
struct EvenNumberSequence: AsyncSequence {
typealias Element = Int
let baseSequence: NumberSequence
func makeAsyncIterator() -> Iterator {
return Iterator(baseIterator: baseSequence.makeAsyncIterator() as! NumberIterator)
}
struct Iterator: AsyncIteratorProtocol {
typealias Element = Int
var baseIterator: NumberIterator
mutating func next() async -> [1] {
while let number = await baseIterator.next() {
if number [2] 2 == 0 {
return number
}
}
return nil
}
}
}The next() method returns an optional Int (Int?). To check if a number is even, use the modulo operator % to test if the remainder when divided by 2 is zero.
Fill all three blanks to create a dictionary from an async sequence where keys are string versions of numbers and values are the numbers themselves, filtering only numbers greater than 1.
func createDictionary(from sequence: NumberSequence) async -> [String: Int] { var result = [String: Int]() var iterator = sequence.makeAsyncIterator() while let number = await [1] { if number [2] 1 { result[[3]] = number } } return result }
To get the next element asynchronously, call await iterator.next(). To filter numbers greater than 1, use >. To use the number as a key in the dictionary, convert it to a string with String(number).