hmhmsh
11/30/2017 - 5:23 AM

## Lambda expression

``````// 要素使って結果を集計したいような場合
func reduce(array: []) {
let i = array.reduce(0) { (num1, num2) -> Int in
num1 + num2
}
// i -> 15
}

func reduce_2(array:[]) {
let s = array.reduce(0, combine: +)
// s -> 15
let k = array.reduce(1, combine: *)
// k -> 120
}

func reduce_dictionary() {
let queries = ["id=3", "token=abc", "tag=5"]

let params = queries.reduce([String: String]()) { (var dict, q) in
// qに各要素が順番にくる
// (dict, q) = ([], "id=3")
// (dict, q) = (["id": "3"], "token=abc")
// (dict, q) = (["id": "3", "token": "abc"], "tag=5")
let v = q.componentsSeparatedByString("=")
let (key, value) = (v[0], v[1])
dict[key] = value
return dict
}
// params -> ["id": "3", "token": "abc", "tag": "5"]
}
``````
``````let array = [1,2,3,4,5]

// 配列内の要素に処理を適用し、その処理を施した配列を使いたい場合
func map(array: []) {
let newArray = array.map { \$0 * 5 }
// newArray -> [5, 10, 15, 20, 25]
}

func map_dictionary() {
let celsius = ["Tokyo":14.0, "Osaka":17.0, "Okinawa":26.0]
let fahrenheit = celsius.map { (\$0.0, 1.8 * \$0.1 + 32) }
// fahrenheit -> [("Okinawa", 78.8), ("Tokyo", 57.2), ("Osaka", 62.6)]
}
``````
``````// 各要素に対して処理を行い、かつ戻り値が必要ない場合
func forEach(array: []) {
array.forEach {
print("\(\$0)")
}
}``````
``````// 条件にマッチする要素のみを取り出したい場合
func filter(array: []) {
let newArray = array.filter { \$0 < 3 }
// newArray -> [1,2]
}``````