實例方法
try
tryReduce(_:_:)
應用 error-throwing 閉包,收集流的每個元素並在完成後發布最終結果。
聲明
func tryReduce<T>(
_ initialResult: T,
_ nextPartialResult: @escaping (T, Self.Output) throws -> T
) -> Publishers.TryReduce<Self, T>
返回值
將閉包應用於所有接收到的元素並在上遊發布者完成時產生累積值的發布者。
參數
initialResult
閉包第一次被調用時收到的值。
nextPartialResult
一個 error-throwing 閉包,它采用 previously-accumulated 值和來自上遊發布者的下一個元素來生成新值。
詳述
使用 Publisher/tryReduce(_:_:)
收集元素流並根據您提供的 error-throwing 閉包生成累積值。如果閉包拋出錯誤,發布者將失敗並將錯誤傳遞給其訂閱者。
在下麵的示例中,發布者的 0
元素導致 myDivide(_:_:)
函數引發錯誤並發布
結果:nan
struct DivisionByZeroError: Error {}
func myDivide(_ dividend: Double, _ divisor: Double) throws -> Double {
guard divisor != 0 else { throw DivisionByZeroError() }
return dividend / divisor
}
var numbers: [Double] = [5, 4, 3, 2, 1, 0]
numbers.publisher
.tryReduce(numbers.first!, { accum, next in try myDivide(accum, next) })
.catch({ _ in Just(Double.nan) })
.sink { print("\($0)") }
可用版本
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 tryFilter(_:)用法及代碼示例
- Swift Result.Publisher tryFirst(where:)用法及代碼示例
- Swift Result.Publisher tryPrefix(while:)用法及代碼示例
- Swift Result.Publisher tryScan(_:_:)用法及代碼示例
- 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 tryReduce(_:_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。