LoginSignup
6
5

More than 5 years have passed since last update.

[iOS][Swift]Swiftのmap, filter, reduceって超便利

Last updated at Posted at 2017-02-18

iOSエンジニアに転職して1月半。
Swiftにもmap,reduce,filterがあることを知った。まぁモダンな言語なら当然だよね。

import UIKit

let arr: [Int] = [1,2,3,4,5,6,7,8,9,10]

// mapで文字列に変換
let strArr: [String] = arr.map{String($0)}
print(strArr)

// filterで奇数を抽出
let odds: [Int] = arr.filter{$0 % 2 != 0}
print(odds)

// reduceで全て足し合わせる!
let total: Int = arr.reduce(0) {$0 + $1}
print(total)

// map,filter,reduceをつなげる
let result: Int = arr.map{$0 * $0}.filter{$0 % 2 != 0}.reduce(0) {$0 + $1}
print(result)

// flatMapでStringの数字をInt型に変換する
let nums: [String] = ["1","2","three","4","5","six","7","8"]
let numsAsInt: [Int] = nums.flatMap{Int($0)} //変換できないものは弾かれる
print(numsAsInt)

Swiftのmap,reduce,filterってもっと書きにくいイメージがあったけど、
それは多分、Trailing Closures($0とか)を使う書き方を知らんかったからかな。
これからバンバン使っていこうと思う。

6
5
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
6
5