Junior — Middle
Can you explain what AsyncSequence is and how it is used in Swift?
sobes.tech AI
Answer from AI
AsyncSequence in Swift is a protocol that allows working with asynchronous sequences of values. It is similar to a regular Sequence but is designed for asynchronously obtaining elements, for example, from a network or other sources where data arrives with a delay.
Using AsyncSequence enables writing code that iterates over elements with the for await construct, making asynchronous data streams convenient to read and process.
Example of using AsyncSequence:
struct AsyncCounter: AsyncSequence {
typealias Element = Int
let limit: Int
struct AsyncIterator: AsyncIteratorProtocol {
var current = 0
let limit: Int
mutating func next() async -> Int? {
guard current < limit else { return nil }
current += 1
// Simulate asynchronous delay
try? await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds
return current
}
}
func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(current: 0, limit: limit)
}
}
// Usage:
Task {
for await number in AsyncCounter(limit: 5) {
print(number)
}
}
This approach is convenient for working with data streams that arrive with a delay, such as web sockets, timers, or asynchronous APIs.