实例方法
reduce(_:
reduce(_:_:)
返回使用给定闭包组合异步序列元素的结果。
声明
func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Self.Element) async throws -> Result
) async rethrows -> Result
返回值
最终累计值。如果序列没有元素,则结果为 initialResult 。
参数
initialResult用作初始累加值的值。
nextPartialResult闭包在闭包第一次运行时接收initialResult。nextPartialResult一个闭包,它将异步序列的一个累加值和一个元素组合成一个新的累加值,用于在
nextPartialResult闭包的下一次调用中使用或返回给调用者。
详述
使用 reduce(_:_:) 方法从整个序列的元素中生成单个值。例如,您可以对一系列数字使用此方法来查找它们的总和或乘积。
nextPartialResult 闭包顺序执行,累积值初始化为 initialResult 和序列的每个元素。
在此示例中,名为 Counter 的异步序列生成从 1 到 4 的 Int 值。 reduce(_:_:) 方法将从异步序列接收到的值相加。
let sum = await Counter(howHigh: 4)
.reduce(0) {
$0 + $1
}
print(sum)
// Prints: 10
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相关用法
- Swift AsyncThrowingFilterSequence drop(while:)用法及代码示例
- Swift AsyncThrowingFilterSequence max(by:)用法及代码示例
- Swift AsyncThrowingFilterSequence min(by:)用法及代码示例
- Swift AsyncThrowingFilterSequence map(_:)用法及代码示例
- Swift AsyncThrowingFilterSequence max()用法及代码示例
- Swift AsyncThrowingFilterSequence contains(_:)用法及代码示例
- Swift AsyncThrowingFilterSequence prefix(_:)用法及代码示例
- Swift AsyncThrowingFilterSequence prefix(while:)用法及代码示例
- Swift AsyncThrowingFilterSequence min()用法及代码示例
- Swift AsyncThrowingFilterSequence filter(_:)用法及代码示例
- Swift AsyncThrowingFilterSequence compactMap(_:)用法及代码示例
- Swift AsyncThrowingFilterSequence flatMap(_:)用法及代码示例
- Swift AsyncThrowingFilterSequence contains(where:)用法及代码示例
- Swift AsyncThrowingFilterSequence allSatisfy(_:)用法及代码示例
- Swift AsyncThrowingFilterSequence dropFirst(_:)用法及代码示例
- Swift AsyncThrowingFilterSequence first(where:)用法及代码示例
- Swift AsyncThrowingFlatMapSequence min()用法及代码示例
- Swift AsyncThrowingFlatMapSequence allSatisfy(_:)用法及代码示例
- Swift AsyncThrowingFlatMapSequence first(where:)用法及代码示例
- Swift AsyncThrowingFlatMapSequence reduce(_:_:)用法及代码示例
- Swift AsyncThrowingFlatMapSequence prefix(while:)用法及代码示例
- Swift AsyncThrowingFlatMapSequence compactMap(_:)用法及代码示例
- Swift AsyncThrowingFlatMapSequence dropFirst(_:)用法及代码示例
- Swift AsyncThrowingFlatMapSequence filter(_:)用法及代码示例
- Swift AsyncThrowingFlatMapSequence prefix(_:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 AsyncThrowingFilterSequence reduce(_:_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
