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

flatMap(_:)

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence. 指定された変換をこのシーケンスの各要素で呼び出す結果を連結したものを含んでいる配列を返します。

Declaration 宣言

func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence

Parameters パラメータ

transform

A closure that accepts an element of this sequence as its argument and returns a sequence or collection. あるクロージャ、それはこのシーケンスのひとつの要素をそれの引数として受け取って、あるシーケンスまたはコレクションを返すものです。

Return Value 戻り値

The resulting flattened array. 結果として生じる平たくされた配列。

Discussion 解説

Use this method to receive a single-level collection when your transformation produces a sequence or collection for each element. あなたの変換が各要素に対してひとつのシーケンスまたはコレクションを生成する場合に、このメソッドを使って単一水準コレクションを受け取ってください。

In this example, note the difference in the result of using map and flatMap with a transformation that returns an array. この例において、mapflatMapをある配列を返す変換とともに使うことの結果における違いに注意してください。


let numbers = [1, 2, 3, 4]


let mapped = numbers.map { Array(repeating: $0, count: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]


let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

In fact, s.flatMap(transform) is equivalent to Array(s.map(transform).joined()). 実際のところ、s.flatMap(transform)Array(s.map(transform).joined())に等しいです。

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

See Also 参照

Transforming an Array 配列の変形