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

flatMap(_:)

Creates an asynchronous sequence that concatenates the results of calling the given transformation with each element of this sequence. ある非同期シーケンスを作成します、それは与えられた変換をこのシーケンスの各要素で呼び出すことの結果を連結します。

Declaration 宣言

func flatMap<SegmentOfResult>(_ transform: @escaping (Element) async -> SegmentOfResult) -> AsyncFlatMapSequence<AsyncThrowingStream<Element, Failure>, SegmentOfResult> where SegmentOfResult : AsyncSequence

Parameters パラメータ

transform

A mapping closure. transform accepts an element of this sequence as its parameter and returns an AsyncSequence. マップを行うクロージャ。transformはこのシーケンスのある要素をそれのパラメータとして受け取り、そしてAsyncSequenceを返します。

Return Value 戻り値

A single, flattened asynchronous sequence that contains all elements in all the asychronous sequences produced by transform. ある単一の、平坦にされた非同期シーケンス、それはtransformによって生み出される全ての非同期シーケンスの中の全ての要素を含みます。

Discussion 解説

Use this method to receive a single-level asynchronous sequence when your transformation produces an asynchronous sequence for each element. このメソッドを使って、単一階層の非同期シーケンスを受け取ってください、あなたの変換が各要素に対してひとつの非同期シーケンスを生み出す時は。

In this example, an asynchronous sequence called Counter produces Int values from 1 to 5. The transforming closure takes the received Int and returns a new Counter that counts that high. For example, when the transform receives 3 from the base sequence, it creates a new Counter that produces the values 1, 2, and 3. The flatMap(_:) method “flattens” the resulting sequence-of-sequences into a single AsyncSequence. この例において、Counterと呼ばれる非同期シーケンスは、Int値を1から5まで生み出します。変換クロージャは、その受け取ったIntをとり、そしてその高さを数える新しいCounterを返します。例えば、変換が3を基底シーケンスから受け取る場合、それは新しいCounterを作成します、そしてそれが値12、そして3を生み出します。flatMap(_:)メソッドは、結果のシーケンスのシーケンスを単一のAsyncSequenceへと “平坦にします”。


let stream = Counter(howHigh: 5)
    .flatMap { Counter(howHigh: $0) }
for await number in stream {
    print("\(number)", terminator: " ")
}
// Prints: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

See Also 参照

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