13
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

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

## 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