1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

1. map

💡 配列の全要素に対して処理を行いたい時に使う!

sample1.swift
// 配列の全要素を5倍するコード
let array = [1, 2, 3, 4, 5]
let mapArray = array.map { $0 * 5 }
print(mapArray) // → [5, 10, 15, 20, 25]

$0 はクロージャの引数の値を省略した形である
$0は第一要素, $1は第二要素を参照している
※mapは辞書型にも利用できる

2. compactMap

💡配列を整理したい時に使う!
配列内にnilがあった場合、nilの要素を除去してくれる

sample2.swift
let array = [3, nil, 10, 1, nil, nil, 7]
let compactMapArray = array.compactMap { $0 }
print(compactMapArray) // -> [3, 10, 1, 7]

また、配列の要素を型変換する時に変換できる値のみを取得することも可能である

sample2-1.swift
// 配列の要素をInt型に変換
let array = ["3", "qiita", "10", "sample", "nil", "/1/", "7"]
let compactMapArray = array.compactMapArray { Int($0) }
print(compactMapArray) // -> [3, 10, 7]

3. filter

💡 条件にマッチする要素のみを取り出したい時に使う!

sample3.swift
// 3未満の数値を取り出している
let array = [1,2,3,4,5]
let filterArray = array.filter { $0 < 3 }
print(filterArray) // → [1, 2]

4. reduce

💡 要素使って結果をまとめたい時に使う!

※第一引数は初期値となる

sample4.swift
// 配列内の要素を全て足し合わせる処理
let array = [1,2,3,4,5]
let reduceValue = array.reduce(0) { (num1, num2) -> Int in 
	num1 + num2
}

print(reduceValue) // 15

// 別の記述方法
array.reduce(0, +) // 15
array.reduce(1, *) // 120
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?