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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。