1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swiftの高階関数をまとめた

Last updated at Posted at 2021-06-22

はじめに

こんにちは@kaneko77です。
今回はSwiftの高階関数についてまとめてみました。
配列の操作でよく使うのでswiftのエンジニアは絶対覚えといて損はないものだと思います。
こちらを参考にしました。

目次

  • map
  • flatMap
  • compactMap
  • filter
  • reduce

紹介

map

配列のデータを一つ一つ引っ張る時に使います。

let test = ["マチュピチュ", "モンサンミッシェル", "サグラダファミリア", "アンコールワット"]
test.map{
    print("データ取得", $0)
}
ログ
データ取得 マチュピチュ
データ取得 モンサンミッシェル
データ取得 サグラダファミリア
データ取得 アンコールワット

flatMap

多重配列を結合する時に使います。

let array = [
    ["hoge1", "hoge2","hoge3"],
    ["huga1", "huga2"]
]
let result = array.flatMap { $0 }
print(result)
ログ
["hoge1", "hoge2", "hoge3", "huga1", "huga2"]

compactMap

配列のデータをキャストする時に使う

let array = ["1", "2", "3", "4", "5"]
let result = array.compactMap{ Int($0) }
print("Stringの配列:", array)
print("Intの配列:", result)
ログ
Stringの配列: ["1", "2", "3", "4", "5"]
Intの配列: [1, 2, 3, 4, 5]

filter

一部データを条件で絞って表示したい時に使います。

let array = [
    (title: "Test1", status: false),
    (title: "Test2", status: true),
    (title: "Test3", status: false),
    (title: "Test4", status: false),
    (title: "Test5", status: true),
    (title: "Test6", status: true)
]
let result = array.filter{ $0.status }
print(result) 
ログ
[(title: "Test2", status: true), (title: "Test5", status: true), (title: "Test6", status: true)]

reduce

現場で使うとしたらこのパターンかな..
配列のデータを足したいときに使います。

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let result = array.reduce(0) { $0 + $1 }
print(result) 
ログ
55

終わりに

今回は高階関数についての簡単な紹介でした。
かなり簡単に配列の操作ができるようになって楽だなっと思いながらいつも使っています。
覚えていない方はこの記事を見てどういう時に使うのかを頭に叩き込んで常に高階関数が使えるかどうか考えながら設計するのも良いと思います。
ここまで読んでいただきありがとうございます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?