實例方法
reduce(_:
reduce(_:_:)
返回使用給定閉包組合序列元素的結果。
聲明
func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Self.Element) throws -> Result
) rethrows -> Result
返回值
最終累計值。如果序列沒有元素,則結果為 initialResult
。
參數
initialResult
用作初始累加值的值。
initialResult
在第一次執行閉包時傳遞給nextPartialResult
。nextPartialResult
一個閉包,它將一個累加值和序列的一個元素組合成一個新的累加值,用於
nextPartialResult
閉包的下一次調用或返回給調用者。
詳述
使用 reduce(_:_:)
方法從整個序列的元素中生成單個值。例如,您可以對一組數字使用此方法來查找它們的總和或乘積。
nextPartialResult
閉包按順序調用,累積值初始化為 initialResult
和序列的每個元素。這個例子展示了如何找到一個數字數組的總和。
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10
調用numbers.reduce(_:_:)
時,會發生以下步驟:
-
nextPartialResult
閉包使用initialResult
(在本例中為0
)和numbers
的第一個元素調用,返回總和:1
。 -
閉包再次使用前一個調用的返回值和序列的每個元素重複調用。
-
當序列耗盡時,從閉包返回的最後一個值返回給調用者。
如果序列沒有元素,則永遠不會執行 nextPartialResult
並且 initialResult
是調用 reduce(_:_:)
的結果。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift DefaultIndices reduce(into:_:)用法及代碼示例
- Swift DefaultIndices randomElement()用法及代碼示例
- Swift DefaultIndices randomElement(using:)用法及代碼示例
- Swift DefaultIndices endIndex用法及代碼示例
- Swift DefaultIndices index(_:offsetBy:limitedBy:)用法及代碼示例
- Swift DefaultIndices prefix(through:)用法及代碼示例
- Swift DefaultIndices min(by:)用法及代碼示例
- Swift DefaultIndices allSatisfy(_:)用法及代碼示例
- Swift DefaultIndices shuffled()用法及代碼示例
- Swift DefaultIndices shuffled(using:)用法及代碼示例
- Swift DefaultIndices first用法及代碼示例
- Swift DefaultIndices prefix(_:)用法及代碼示例
- Swift DefaultIndices lexicographicallyPrecedes(_:)用法及代碼示例
- Swift DefaultIndices index(_:offsetBy:)用法及代碼示例
- Swift DefaultIndices compactMap(_:)用法及代碼示例
- Swift DefaultIndices suffix(_:)用法及代碼示例
- Swift DefaultIndices dropLast(_:)用法及代碼示例
- Swift DefaultIndices last(where:)用法及代碼示例
- Swift DefaultIndices filter(_:)用法及代碼示例
- Swift DefaultIndices lastIndex(of:)用法及代碼示例
- Swift DefaultIndices contains(_:)用法及代碼示例
- Swift DefaultIndices max(by:)用法及代碼示例
- Swift DefaultIndices prefix(upTo:)用法及代碼示例
- Swift DefaultIndices split(separator:maxSplits:omittingEmptySubsequences:)用法及代碼示例
- Swift DefaultIndices contains(where:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 DefaultIndices reduce(_:_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。