Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

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]

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした