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

flatMap(_:)

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

Declaration 宣言

func flatMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

Parameters パラメータ

transform

A closure that accepts an element of this sequence as its argument and returns an optional value. あるクロージャ、それはこのシーケンスのひとつの要素をそれの引数として受け取って、ひとつのオプショナルの値を返すものです。

Return Value 戻り値

An array of the non-nil results of calling transform with each element of the sequence. シーケンスの各要素でtransformを呼ぶことの非nilの結果の配列。

Discussion 解説

Use this method to receive an array of nonoptional values when your transformation produces an optional value. あなたの変換がオプショナル値を生成する場合に、このメソッドを使って非オプショナル値からなる配列を受け取ってください。

In this example, note the difference in the result of using map and flatMap with a transformation that returns an optional Int value. この例において、mapflatMapを、オプショナルInt値を返す変換とともに使う結果の違いに注意してください。


let possibleNumbers = ["1", "2", "three", "///4///", "5"]


let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]


let flatMapped: [Int] = possibleNumbers.flatMap { str in Int(str) }
// [1, 2, 5]

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