LoginSignup
188
185

More than 5 years have passed since last update.

[Swift]これは覚えたい!!filter、map、reduceを使うとスゴい便利だった

Last updated at Posted at 2014-12-23

俺の名はケンヤ。難事件をいくつも迷宮入りさせたニート。しかし ある時謎の組織に入社し薬を飲まされ身体が縮んで Braian になっちゃった。

reduce 配列内を足し算

reduceは配列内の合計値が計算できる

var plus = { (a: Int, b: Int) -> Int in a + b }

var num = [0, 1, 2, 3, 4, 5].reduce(0, plus)
println(num)
// 15が出力される

filter 配列をフィルタリング

filterは配列のフィルタリング
0〜10の配列内の値を偶数でフィルタリングして抜き出す

var filterA = {
    (a: Int) -> Bool in a% 2 == 0
}

var filterResult = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filetr(filetrA)
println(filterResult)
// [0, 2, 4, 6, 8, 10]が出力される

map 配列の変更

mapは配列内の値を変更する
0〜5の値を2倍する

var mapMultiply = { (a: Int) -> in a * 2 }

var mapResult = [0, 1, 2, 3, 4, 5].map(mapMultiply)
println(mapResult) 
// [0, 2, 4, 6, 8, 10]

map、filter、reduceを使ってチェーンさせる

 let numbers: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 let result = numbers.map({ (value: Int) -> Int in return value * 2})
.filter({ (value: Int) -> Bool in value % 4 == 0})
.reduce(0, {(a: Int, b: Int) -> Int in a + b})
result
// 60

めっちゃ便利ですね。関数つくるのが苦手なので慣れたいです。
今回はメモ用として書きました。
Swiftは日本語の情報が少ないので大変です。

188
185
1

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
188
185