實例方法
try
tryScan(_:_:)
通過將當前元素與閉包返回的最後一個值一起提供給 error-throwing 閉包來轉換來自上遊發布者的元素。
聲明
func tryScan<T>(
_ initialResult: T,
_ nextPartialResult: @escaping (T, Self.Output) throws -> T
) -> Publishers.TryScan<Self, T>
返回值
一個發布者,它通過應用一個閉包來轉換元素,該閉包接收其先前的返回值和來自上遊發布者的下一個元素。
參數
initialResult
nextPartialResult
閉包返回的先前結果。nextPartialResult
一個 error-throwing 閉包,它的參數是閉包返回的前一個值和上遊發布者發出的下一個元素。
詳述
使用 Publisher/tryScan(_:_:)
將所有 previously-published 值累積為單個值,然後將其與每個 newly-published 值組合。如果您的累加器閉包引發錯誤,則發布者會因錯誤而終止。
在下麵的示例中,Publisher/tryScan(_:_:)
對集合發布者的元素調用除法函數。 Publishers/TryScan
發布者發布每個結果,直到函數遇到 DivisionByZeroError
,這會終止發布者。
struct DivisionByZeroError: Error {}
/// A function that throws a DivisionByZeroError if `current` provided by the TryScan publisher is zero.
func myThrowingFunction(_ lastValue: Int, _ currentValue: Int) throws -> Int {
guard currentValue != 0 else { throw DivisionByZeroError() }
return (lastValue + currentValue) / currentValue
}
let numbers = [1,2,3,4,5,0,6,7,8,9]
cancellable = numbers.publisher
.tryScan(10) { try myThrowingFunction($0, $1) }
.sink(
receiveCompletion: { print ("\($0)") },
receiveValue: { print ("\($0)", terminator: " ") }
)
// Prints: "11 6 3 1 1 -1 failure(DivisionByZeroError())".
如果閉包拋出錯誤,則發布者會因錯誤而失敗。
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher tryCompactMap(_:)用法及代碼示例
- Swift Result.Publisher tryCatch(_:)用法及代碼示例
- Swift Result.Publisher tryReduce(_:_:)用法及代碼示例
- Swift Result.Publisher tryFilter(_:)用法及代碼示例
- Swift Result.Publisher tryFirst(where:)用法及代碼示例
- Swift Result.Publisher tryPrefix(while:)用法及代碼示例
- Swift Result.Publisher tryMap(_:)用法及代碼示例
- Swift Result.Publisher tryDrop(while:)用法及代碼示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代碼示例
- Swift Result.Publisher throttle(for:scheduler:latest:)用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:)用法及代碼示例
- Swift Result.Publisher print(_:to:)用法及代碼示例
- Swift Result.Publisher sink(receiveValue:)用法及代碼示例
- Swift Result.Publisher eraseToAnyPublisher()用法及代碼示例
- Swift Result.Publisher setFailureType(to:)用法及代碼示例
- Swift Result.Publisher first(where:)用法及代碼示例
- Swift Result.Publisher output(at:)用法及代碼示例
- Swift Result.Publisher dropFirst(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代碼示例
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher catch(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result.Publisher tryScan(_:_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。