LoginSignup
2
1

More than 5 years have passed since last update.

配列操作

Last updated at Posted at 2016-11-08

勉強したことまとめ

filter

条件マッチするものを新たな配列に格納していく。
以下は、文字数が3文字以上のものを抽出。

filter.swift
let strings = ["AB", "CDEF", "GHIJKLM" , "NOP"]

let resultStrings = strings.filter {
    $0.characters.count >= 3
}
//["CDEF", "GHIJKL", "NOP"]

reduce

要素をまとめて一つの値を返す。
※reduce(n) nは初期値
第一引数:今の値
第二引数:配列の要素(配列の場合は先頭から)

reduce.swift
let numbers = [9, 8, 3, 7, 6]
let sum = numbers.reduce(1) {
    return $0 * $1
}
//sum 9072

ちなみにStringも

reduce2.swift
let strings = ["A", "B", "C", "D", "E"]
let stringConcatenation = strings.reduce("alphabet: ") {
    $0 + $1
}
// alphabet: ABCDE

map

すべての要素に同じ処理し、新たな配列を返す。
※辞書はランダムに取り出される。

map.swift
let goods = ["Chocolate": 200, "Banana": 100, "Juice": 150]
let prices = goods.map {
    Int(Double($0.value) * 1.08)
}
//[216, 162, 108]

まとめ

めちゃくちゃまとまってる記事がありました。。。
http://qiita.com/motokiee/items/cf83b22cb34921580a52

クロージャは書き方(というか省略?)がたくさんあるので状況に適した書き方ができるようになりたい。

2
1
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
2
1