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

reduce(into:_:)

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

Declaration 宣言

func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Base.Element) throws -> ()) rethrows -> Result

Parameters パラメータ

initialResult

The value to use as the initial accumulating value. 最初から蓄積されている値として使われる値。

updateAccumulatingResult

A closure that updates the accumulating value with an element of the sequence. 蓄積される値をこのシーケンスのある要素を使って更新するクロージャ。

Return Value 戻り値

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

Discussion 解説

Use the reduce(into:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of integers to filter adjacent equal entries or count frequencies. reduce(into:_:)メソッドを使って、あるシーケンス全体の要素それらからある単一の値を生成してください。例えば、あなたはこのメソッドを整数からなる配列で使うことで、隣接する同等の項目をフィルタしたり頻度を数えたりできます。

This method is preferred over reduce(_:_:) for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary. このメソッドは、効率のためにreduce(_:_:)より好まれます、その結果がコピーオンライト型である場合、例えばArrayまたは辞書に対しては。

The updateAccumulatingResult closure is called sequentially with a mutable accumulating value initialized to initialResult and each element of the sequence. This example shows how to build a dictionary of letter frequencies of a string. updateAccumulatingResultクロージャは、initialResultへと初期化された可変の蓄積値とシーケンスの各要素とともに連続して呼び出されます。この例は、ある文字列の文字頻度の辞書を作り上げる方法を示します。


let letters = "abracadabra"
let letterCount = letters.reduce(into: [:]) { counts, letter in
    counts[letter, default: 0] += 1
}
// letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]

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

  1. The updateAccumulatingResult closure is called with the initial accumulating value—[:] in this case—and the first character of letters, modifying the accumulating value by setting 1 for the key "a". updateAccumulatingResultクロージャが、初期蓄積値—この場合では[:]—そしてlettersの最初の文字とともに呼び出されて、1をキー"a"に対して設定することで蓄積値を修正します。

  2. The closure is called again repeatedly with the updated accumulating value and each element of the sequence. クロージャは、更新された蓄積値とシーケンスの各要素とともに繰り返して再び呼び出されます。

  3. When the sequence is exhausted, the accumulating value is returned to the caller. シーケンスが使い尽くされる時、蓄積値が呼び出し側へ返されます。

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

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