AsyncIteratorProtocol
声明
@rethrows protocol AsyncIteratorProtocol
概述
AsyncIteratorProtocol 定义AsyncSequence 协议的makeAsyncIterator() 方法返回的类型。简而言之,迭代器是产生异步序列值的东西。该协议定义了一个异步方法 next() ,它或者产生序列的下一个元素,或者返回 nil 以表示序列的结束。
要实现您自己的 AsyncSequence ,请实现符合 AsyncIteratorProtocol 的包装类型。以下示例显示了 Counter 类型,该类型使用内部迭代器单调生成 Int 值,直到达到 howHigh 值。虽然这个例子本身不是异步的,但它展示了自定义序列和迭代器的形状,以及如何像异步一样使用它:
struct Counter : AsyncSequence {
typealias Element = Int
let howHigh: Int
struct AsyncIterator : AsyncIteratorProtocol {
let howHigh: Int
var current = 1
mutating func next() async -> Int? {
// A genuinely asychronous implementation uses the `Task`
// API to check for cancellation here and return early.
guard current <= howHigh else {
return nil
}
let result = current
current += 1
return result
}
}
func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(howHigh: howHigh)
}
}
在调用站点,这看起来像:
for await i in Counter(howHigh: 10) {
print(i, terminator: " ")
}
// Prints: 1 2 3 4 5 6 7 8 9 10
迭代结束
迭代器返回nil 以指示序列的结束。从 next() 返回 nil (或抛出错误)后,迭代器进入终止状态,并且所有未来对 next() 的调用都必须返回 nil 。
消除
符合 AsyncIteratorProtocol 的类型应该使用 Swift 的 Task API 提供的取消原语。迭代器可以选择如何处理和响应取消,包括:
-
检查
next()中当前Task的isCancelled值并返回nil以终止序列。 -
在
Task上调用checkCancellation()会引发CancellationError。 -
使用
withTaskCancellationHandler(handler:operation:)调用实现next()以立即对取消做出反应。
如果迭代器需要在取消时进行清理,它可以在如上所述检查取消之后进行清理,或者如果它是引用类型,则在 deinit 中进行。
可用版本
相关用法
- Swift AsyncThrowingFlatMapSequence min()用法及代码示例
- Swift AsyncPrefixWhileSequence reduce(_:_:)用法及代码示例
- Swift AsyncThrowingMapSequence reduce(_:_:)用法及代码示例
- Swift AsyncDropWhileSequence allSatisfy(_:)用法及代码示例
- Swift AsyncSequence dropFirst(_:)用法及代码示例
- Swift AsyncDropFirstSequence filter(_:)用法及代码示例
- Swift AsyncSequence reduce(_:_:)用法及代码示例
- Swift AsyncFlatMapSequence min()用法及代码示例
- Swift AsyncThrowingPrefixWhileSequence drop(while:)用法及代码示例
- Swift AsyncThrowingMapSequence contains(_:)用法及代码示例
- Swift AsyncPrefixWhileSequence compactMap(_:)用法及代码示例
- Swift AsyncSequence first(where:)用法及代码示例
- Swift AsyncPrefixSequence dropFirst(_:)用法及代码示例
- Swift AsyncPrefixWhileSequence min()用法及代码示例
- Swift AsyncThrowingPrefixWhileSequence filter(_:)用法及代码示例
- Swift AsyncThrowingDropWhileSequence first(where:)用法及代码示例
- Swift AsyncSequence prefix(_:)用法及代码示例
- Swift AsyncStream用法及代码示例
- Swift AsyncPrefixWhileSequence contains(where:)用法及代码示例
- Swift AsyncSequence map(_:)用法及代码示例
- Swift AsyncThrowingCompactMapSequence drop(while:)用法及代码示例
- Swift AsyncThrowingFilterSequence drop(while:)用法及代码示例
- Swift AsyncThrowingCompactMapSequence prefix(while:)用法及代码示例
- Swift AsyncThrowingDropWhileSequence flatMap(_:)用法及代码示例
- Swift AsyncThrowingStream filter(_:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 AsyncIteratorProtocol。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
