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

reduce(_:_:)

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

Declaration 宣言

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

Parameters パラメータ

initialResult

The value to use as the initial accumulating value. The nextPartialResult closure receives initialResult the first time the closure runs. 最初から蓄積されている値として使われる値。nextPartialResultは、initialResultを、クロージャが動作する最初の時に受け取ります。

nextPartialResult

A closure that combines an accumulating value and an element of the asynchronous sequence into a new accumulating value, for use 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 sequence of numbers to find their sum or product. reduce(_:_:)メソッドを使って、あるシーケンス全体の要素それらからある単一の値を生成してください。例えば、あなたはこのメソッドを数値からなるシーケンス上で使うことで、それらの和または積を見つけます。

The nextPartialResult closure executes sequentially with an accumulating value initialized to initialResult and each element of the sequence. nextPartialResultクロージャは、initialResultへと初期化された蓄積値とそのシーケンスの各要素を使って連続して遂行します。

In this example, an asynchronous sequence called Counter produces Int values from 1 to 4. The reduce(_:_:) method sums the values received from the asynchronous sequence. この例において、Counterと呼ばれる非同期シーケンスはInt値を1から4まで生み出します。reduce(_:_:)メソッドは、非同期シーケンスから受け取った値それらを合計します。


let sum = await Counter(howHigh: 4)
    .reduce(0) {
        $0 + $1
    }
print(sum)
// Prints: 10

See Also 参照

Transforming a Sequence シーケンスを変形する