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

compactMap(_:)

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

Declaration 宣言

func compactMap<ElementOfResult>(_ transform: (Base.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 non-optional values when your transformation produces an optional value. このメソッドを使うことで非オプショナル値の配列を受け取ってください、あなたの変換がオプショナル値を生成する時に。

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


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


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


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

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は結果の長さです。