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

flatMap(_:)

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

Declaration 宣言

func flatMap<SegmentOfResult>(_ transform: @escaping (ChildTaskResult) async throws -> SegmentOfResult) -> AsyncThrowingFlatMapSequence<ThrowingTaskGroup<ChildTaskResult, Failure>, SegmentOfResult> where SegmentOfResult : AsyncSequence

Parameters パラメータ

transform

An error-throwing mapping closure. transform accepts an element of this sequence as its parameter and returns an AsyncSequence. If transform throws an error, the sequence ends. あるエラースローマッピングクロージャ。transformはこのシーケンスのある要素をそれのパラメータとして受け取り、そしてAsyncSequenceを返します。transformがエラーをスローするならば、そのシーケンスは終わります。

Return Value 戻り値

A single, flattened asynchronous sequence that contains all elements in all the asychronous sequences produced by transform. The sequence ends either when the the last sequence created from the last element from base sequence ends, or when transform throws an error. ある単一の、平坦にされた非同期シーケンス、それは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. However, when the closure receives 4, it throws an error, terminating the sequence. この例において、Counterと呼ばれる非同期シーケンスは、Int値を1から5まで生み出します。変換クロージャは、その受け取ったIntをとり、そしてその高さを数える新しいCounterを返します。例えば、変換が3を基底シーケンスから受け取る場合、それは新しいCounterを作成します、そしてそれが値12、そして3を生み出します。flatMap(_:)メソッドは、結果のシーケンスのシーケンスを単一のAsyncSequenceへと “平坦にします”。しかしながら、クロージャが4を受け取る場合、それはシーケンスを終端して、エラーをスローします。


do {
    let stream = Counter(howHigh: 5)
        .flatMap { (value) -> Counter in
            if value == 4 {
                throw MyError()
            }
            return Counter(howHigh: value)
        }
    for try await number in stream {
        print ("\(number)", terminator: " ")
    }
} catch {
    print(error)
}
// Prints: 1 1 2 1 2 3 MyError()

See Also 参照

Accessing an Asynchronous Sequence of Results 結果それらからなるある非同期シーケンスにアクセスする