實例方法
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 AsyncMapSequence max()用法及代碼示例
- Swift AsyncMapSequence min()用法及代碼示例
- Swift AsyncMapSequence compactMap(_:)用法及代碼示例
- Swift AsyncMapSequence contains(_:)用法及代碼示例
- Swift AsyncMapSequence max(by:)用法及代碼示例
- Swift AsyncMapSequence contains(where:)用法及代碼示例
- Swift AsyncMapSequence map(_:)用法及代碼示例
- Swift AsyncMapSequence first(where:)用法及代碼示例
- Swift AsyncMapSequence drop(while:)用法及代碼示例
- Swift AsyncMapSequence min(by:)用法及代碼示例
- Swift AsyncMapSequence prefix(_:)用法及代碼示例
- Swift AsyncMapSequence flatMap(_:)用法及代碼示例
- Swift AsyncMapSequence prefix(while:)用法及代碼示例
- Swift AsyncMapSequence allSatisfy(_:)用法及代碼示例
- Swift AsyncMapSequence filter(_:)用法及代碼示例
- Swift AsyncMapSequence dropFirst(_:)用法及代碼示例
- Swift AsyncThrowingFlatMapSequence min()用法及代碼示例
- Swift AsyncPrefixWhileSequence reduce(_:_:)用法及代碼示例
- Swift AsyncThrowingMapSequence reduce(_:_:)用法及代碼示例
- Swift AsyncDropWhileSequence allSatisfy(_:)用法及代碼示例
- Swift AsyncSequence dropFirst(_:)用法及代碼示例
- Swift AsyncDropFirstSequence filter(_:)用法及代碼示例
- Swift AsyncSequence reduce(_:_:)用法及代碼示例
- Swift AsyncFlatMapSequence min()用法及代碼示例
- Swift AsyncThrowingPrefixWhileSequence drop(while:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 AsyncMapSequence reduce(_:_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。