实例方法
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(_:_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。