初始化器
init(unfolding:)
從給定的 element-producing 閉包構造一個異步拋出流。
聲明
init(unfolding produce: @escaping () async throws -> Element?) where Failure == Error
參數
produce
為流異步生成元素的閉包。
詳述
當您有一個可以為流生成元素的異步函數並且不想手動調用延續時,請使用此便捷初始化程序。這個初始化器“unfolds” 你的閉包變成了一個full-blown 異步流。創建的流會自動處理對AsyncSequence
協議的遵守情況。要以錯誤終止流,請從閉包中拋出錯誤。
以下示例顯示了使用此初始化程序創建的 AsyncThrowingStream
,該初始化程序在 one-second 間隔上生成隨機數。如果隨機數可被 5 整除且沒有餘數,則流將拋出 MyRandomNumberError
。
let stream = AsyncThrowingStream<Int, Error> {
await Task.sleep(1 * 1_000_000_000)
let random = Int.random(in: 1...10)
if (random % 5 == 0) {
throw MyRandomNumberError()
}
return random
}
// Call point:
do {
for try await random in stream {
print ("\(random)")
}
} catch {
print ("\(error)")
}
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift AsyncThrowingStream init(_:bufferingPolicy:_:)用法及代碼示例
- Swift AsyncThrowingStream filter(_:)用法及代碼示例
- Swift AsyncThrowingStream max(by:)用法及代碼示例
- Swift AsyncThrowingStream contains(where:)用法及代碼示例
- Swift AsyncThrowingStream map(_:)用法及代碼示例
- Swift AsyncThrowingStream prefix(_:)用法及代碼示例
- Swift AsyncThrowingStream min(by:)用法及代碼示例
- Swift AsyncThrowingStream allSatisfy(_:)用法及代碼示例
- Swift AsyncThrowingStream contains(_:)用法及代碼示例
- Swift AsyncThrowingStream compactMap(_:)用法及代碼示例
- Swift AsyncThrowingStream reduce(_:_:)用法及代碼示例
- Swift AsyncThrowingStream first(where:)用法及代碼示例
- Swift AsyncThrowingStream drop(while:)用法及代碼示例
- Swift AsyncThrowingStream flatMap(_:)用法及代碼示例
- Swift AsyncThrowingStream min()用法及代碼示例
- Swift AsyncThrowingStream prefix(while:)用法及代碼示例
- Swift AsyncThrowingStream max()用法及代碼示例
- Swift AsyncThrowingStream dropFirst(_:)用法及代碼示例
- Swift AsyncThrowingStream用法及代碼示例
- Swift AsyncThrowingFlatMapSequence min()用法及代碼示例
- Swift AsyncThrowingMapSequence reduce(_:_:)用法及代碼示例
- Swift AsyncThrowingPrefixWhileSequence drop(while:)用法及代碼示例
- Swift AsyncThrowingMapSequence contains(_:)用法及代碼示例
- Swift AsyncThrowingPrefixWhileSequence filter(_:)用法及代碼示例
- Swift AsyncThrowingDropWhileSequence first(where:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 AsyncThrowingStream init(unfolding:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。