Generic Instance Method 総称体インスタンスメソッド

reduce(_:_:)

Returns the result of combining the elements of the sequence using the given closure. 与えられたクロージャを使って、このシーケンスの要素それらを結合する結果を返します。

Declaration 宣言

func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

Parameters パラメータ

initialResult

The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed. 最初から蓄積されている値として使われる値。initialResultnextPartialResultに、クロージャが実行される最初の時に渡されます。

nextPartialResult

A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller. あるクロージャ、それは蓄積値をシーケンスのいち要素と結合して新しい蓄積値とし、nextPartialResultクロージャの次の呼び出しにおいて使われるか、呼び出し側に返されるようにします。

Return Value 戻り値

The final accumulated value. If the sequence has no elements, the result is initialResult. 最終的に蓄積された値。シーケンスが1つも要素を持たないならば、結果はinitialResultです。

Discussion 解説

Use the reduce(_:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product. reduce(_:_:)メソッドを使って、あるシーケンス全体の要素それらからある単一の値を生成してください。例えば、あなたはこのメソッドを数値いくつかからなる配列で使うことで、それらの和または積を見つけます。

The nextPartialResult closure is called sequentially with an accumulating value initialized to initialResult and each element of the sequence. This example shows how to find the sum of an array of numbers. nextPartialResultクロージャは、initialResultへと初期化された蓄積値とシーケンスの各要素とともに連続して呼び出されます。この例は、どのように数からなる配列の合計を見出すかを示します。


let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
    x + y
})
// numberSum == 10

When numbers.reduce(_:_:) is called, the following steps occur: numbers.reduce(_:_:)が呼び出される時、以下の段階が生じます:

  1. The nextPartialResult closure is called with initialResult0 in this case—and the first element of numbers, returning the sum: 1. nextPartialResultクロージャが、initialResult—この場合では0—そしてnumbersの最初の要素とともに呼び出されて、その合計:1を返します。

  2. The closure is called again repeatedly with the previous call’s return value and each element of the sequence. クロージャは、前の呼び出しの戻り値とシーケンスの各要素とともに繰り返して再び呼び出されます。

  3. When the sequence is exhausted, the last value returned from the closure is returned to the caller. シーケンスが使い尽くされる時、クロージャから返される最後の値が呼び出し側へ返されます。

If the sequence has no elements, nextPartialResult is never executed and initialResult is the result of the call to reduce(_:_:). シーケンスが1つも要素を持たないならば、nextPartialResultは決して実行されません、そしてinitialResultreduce(_:_:)への呼び出しの結果となります。

Complexity: O(n), where n is the length of the sequence. 計算量:O(n)、ここでnはシーケンスの長さです。

See Also 参照

Transforming an Array 配列の変形