實例方法
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 Optional.Publisher removeDuplicates()用法及代碼示例
- Swift Optional.Publisher receive(on:options:)用法及代碼示例
- Swift Optional.Publisher replaceNil(with:)用法及代碼示例
- Swift Optional.Publisher tryDrop(while:)用法及代碼示例
- Swift Optional.Publisher debounce(for:scheduler:options:)用法及代碼示例
- Swift Optional.Publisher breakpoint(receiveSubscription:receiveOutput:receiveCompletion:)用法及代碼示例
- Swift Optional.Publisher mapError(_:)用法及代碼示例
- Swift Optional.Publisher catch(_:)用法及代碼示例
- Swift Optional.Publisher tryAllSatisfy(_:)用法及代碼示例
- Swift Optional.Publisher zip(_:_:_:)用法及代碼示例
- Swift Optional.Publisher sink(receiveValue:)用法及代碼示例
- Swift Optional.Publisher scan(_:_:)用法及代碼示例
- Swift Optional.Publisher throttle(for:scheduler:latest:)用法及代碼示例
- Swift Optional.Publisher assertNoFailure(_:file:line:)用法及代碼示例
- Swift Optional.Publisher collect(_:)用法及代碼示例
- Swift Optional.Publisher combineLatest(_:_:_:_:)用法及代碼示例
- Swift Optional.Publisher share()用法及代碼示例
- Swift Optional.Publisher merge(with:_:_:)用法及代碼示例
- Swift Optional.Publisher map(_:_:)用法及代碼示例
- Swift Optional.Publisher assign(to:on:)用法及代碼示例
- Swift Optional.Publisher zip(_:_:_:_:)用法及代碼示例
- Swift Optional.Publisher output(in:)用法及代碼示例
- Swift Optional.Publisher tryReduce(_:_:)用法及代碼示例
- Swift Optional.Publisher map(_:_:_:)用法及代碼示例
- Swift Optional.Publisher prepend(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Optional.Publisher reduce(_:_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。