LoginSignup
33
35

More than 5 years have passed since last update.

FunctionalなSwiftのmap, filter, reduceのススメ

Last updated at Posted at 2016-02-03

概要

おもに配列を扱う便利なmap, filter, reduceを使わない例と対比します。
チートシートとしての使用を想定してます。

map

お題

ある配列から各要素に対して自乗し、新しい配列を作りたい!

宜しくない書き方

varを使いappend()する方法

func square(x: Int) -> Int {
  return x * x
}
var a = [1, 2, 3, 4, 5]
var b = [Int]()

for x in a {
  b.append(square(x))
}

mapヲ使用スベシ1

func square(x: Int) -> Int {
  return x * x
}

let a = [1, 2, 3, 4, 5]
let b = a.map { x in
  square(x)
}

mapヲ使用スベシ2

関数を引数とするケース

func square(x: Int) -> Int {
  return x * x
}

let a = [1, 2, 3, 4, 5]
let b = a.map(square) // [1, 4, 9, 16, 25]

mapヲ使用スベシ3

ここでショートハンド引数を使用。1行で書ける。

[1, 2, 3, 4, 5].map { $0 * $0 } // [1, 4, 9, 16, 25]

15より大の配列もfilter使うととても簡略に書ける!

[1, 2, 3, 4, 5].map { $0 * $0 }.filter { $0 > 15 } // [16, 25]

filter

ある条件を満たすオブジェクトを配列に追加するケース

お題

gradeが90より大のStudentオブジェクトの一覧 (bestStudents)が欲しい!

宜しくない書き方

varを使いappend()する方法

var bestStudents = [Student]()

for student in students {
  if student.grade > 90 {
    bestStudents.append(student)
  }
}

filterヲ使用スベシ1

ここでショートハンド引数を使用。簡潔になる。

let besetStudents = students.filter { $0.grade > 90 }

filterヲ使用スベシ2(関数を渡す)

引数として関数を渡すケース。

func isBestStudent(student: Student) -> Bool {
  return student.grade > 90
}

let bestStudents = students.filer(isBestStudent)

reduce

配列の要素を畳み込む。

お題

1,2,3,4,5を要素に持つ配列の要素を積み上げ、その総和を求めたい!

宜しくない書き方

varを使い、for inで積み上げる。

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

var sum = 0
for x in a {
  sum += x
}

reduceヲ使用スベシ1

リストの畳込み時は、reduceを使う。

let a = [1, 2, 3, 4, 5]
let sum = a.reduce(0) { (total, value) in
  return total + value
}

解説

初期値0が下表#1のtotalになり、resultが次iterationの(#1...5それぞれ)のtotalになる。

iteration total: U value: T result
#1 0 1 1
#2 1 2 3
#3 3 3 6
#4 6 4 10
#5 10 5 15

reduceヲ使用スベシ2

ここでショートハンド引数を使用。

let a = [1, 2, 3, 4, 5]
let sum = a.reduce(0) { $0 + $1 } // 15

reduceヲ使用スベシ3

+が渡せる!

let a = [1, 2, 3, 4, 5]
let sum = a.reduce(0, combine: +) // 15

参考文献
1. 7 Habits For a More Functional Swift

2. Swift Functional Programming Tutorial

33
35
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
33
35