LoginSignup
19
13

More than 5 years have passed since last update.

Swiftの配列操作(map,reduce,filter)

Posted at

今回ご紹介するのは、配列操作のメソッドについてです。
今更感はありますが、お付き合いください。

map

配列の全ての要素に対して、順に処理を行い新しい配列として返します。
※$0の引数には配列の要素が入ります。

 let list = [1, 2, 3, 4, 5]

 let result = list.map({ $0 * 2 })

 print(result) // [2, 4, 6, 8, 10]

reduce

配列の要素の集計を行いたい時に使用します
クロージャには合計式を書き、第一引数に初期値をいれます。

let list = [1, 2, 3, 4, 5]

let total1 = list.reduce(0){ $0 + $1 }
let total2 = list.reduce(1, combine: { $0 * $1 })

print(total1) // 15
print(total2) // 120

filter

配列をクロージャ部分の条件によってフィルタリングし、新しい配列として返します。

let list = [1, 2, 3, 4, 5]

let result = list.filter({ $0 % 2 == 0 })

print(result) // [2,4]

条件をメソッドに分けてフィルタリングすることもできます。

func calc(x: Int) -> Bool {
    if x % 2 == 0 {
        return true
    } else {
        return false
    }
}

let list = [1, 2, 3, 4, 5]

let result = list.filter({ calc($0) })

print(result) // [2,4]

ざっと簡潔に書きましたが、使いこなせるとより良いコードが掛けそうですね。

19
13
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
19
13