實例方法
reduce(_:
reduce(_:_:)
應用一個閉包,該閉包收集流的每個元素並在完成時發布最終結果。
聲明
func reduce<T>(
_ initialResult: T,
_ nextPartialResult: @escaping (T, Self.Output) -> T
) -> Publishers.Reduce<Self, T>
返回值
將閉包應用於所有接收到的元素並在上遊發布者完成時產生累積值的發布者。如果Publisher/reduce(_:_:)
收到上遊發布者的錯誤,操作者將其傳遞給下遊訂閱者,發布者終止並且不發布任何值。
參數
initialResult
閉包第一次被調用時收到的值。
nextPartialResult
一個閉包,通過獲取 previously-accumulated 值和它從上遊發布者接收的下一個元素來生成新值。
詳述
使用Publisher/reduce(_:_:)
收集元素流並根據您提供的閉包生成累積值。
在以下示例中,Publisher/reduce(_:_:)
運算符收集它從上遊發布者接收到的所有整數值:
let numbers = (0...10)
cancellable = numbers.publisher
.reduce(0, { accum, next in accum + next })
.sink { print("\($0)") }
// Prints: "55"
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift Result.Publisher receive(on:options:)用法及代碼示例
- Swift Result.Publisher replaceNil(with:)用法及代碼示例
- Swift Result.Publisher removeDuplicates()用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Result.Publisher tryLast(where:)用法及代碼示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:)用法及代碼示例
- Swift Result.Publisher tryCompactMap(_:)用法及代碼示例
- 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 tryCatch(_:)用法及代碼示例
- Swift Result.Publisher dropFirst(_:)用法及代碼示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代碼示例
- Swift Result.Publisher flatMap(maxPublishers:_:)用法及代碼示例
- Swift Result.Publisher map(_:_:_:)用法及代碼示例
- Swift Result.Publisher catch(_:)用法及代碼示例
- Swift Result.Publisher drop(while:)用法及代碼示例
- Swift Result.Publisher prefix(_:)用法及代碼示例
- Swift Result.Publisher timeout(_:scheduler:options:customError:)用法及代碼示例
- Swift Result.Publisher merge(with:_:)用法及代碼示例
- Swift Result.Publisher map(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Result.Publisher reduce(_:_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。