0
2

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 1 year has passed since last update.

Swiftで、map, filter, reduceの使い方

Posted at

配列を操作するときに使うメソッドですね。

全体のコードはこんな感じです。

// 文字列の配列を作成します
let words = ["apple", "banana", "cherry"]

// mapを使用して各要素の文字数を取得します
let wordLengths = words.map { $0.count }
// 結果: [5, 6, 6]

// filterを使用して5文字以上の単語のみを抽出します
let longWords = words.filter { $0.count >= 5 }
// 結果: ["apple", "banana", "cherry"]

// reduceを使用して全ての単語を結合します
let sentence = words.reduce("", { $0 + " " + $1 })
// 結果: " apple banana cherry"

filterを使った例

filterメソッドは、配列の値で条件に合うものだけ取り出すものです。

// filterは、コレクションの要素を条件に従ってフィルタリングするメソッドです。
let fruits = ["apple", "banana", "orange", "grape", "peach"]

// appleだけを取り出した配列を作る
let apple = fruits.filter { $0 == "apple" }
print(apple)

// appleとgrapeを除いた配列を作る
let filteredFruits = fruits.filter { $0 != "apple" && $0 != "grape" }
print(filteredFruits)

mapを使った例

mapメソッドは、配列の要素を変換した新しい配列を作成する。

let fruits = ["apple", "banana", "orange", "grape", "peach"]

// 例1: 配列の要素を大文字に変換する
let uppercasedFruits = fruits.map { $0.uppercased() }
print(uppercasedFruits) // ["APPLE", "BANANA", "ORANGE", "GRAPE", "PEACH"]

// 例2: 配列の要素をInt型に変換する
let numbers = ["1", "2", "3", "4", "5"]
let intNumbers = numbers.map { Int($0) }

// 例3: 配列の要素を新しく作成した構造体に変換する
// 多次元配列で、商品名と値段を書く
let goods = [["name": "apple", "price": 100], ["name": "banana", "price": 200], ["name": "orange", "price": 300]]

// 商品名と値段を格納する構造体
struct Goods: CustomStringConvertible {
    let name: String
    let price: Int

    var description: String {
        return "Goods(name: \(name), price: \(price))"
    }
}

// 構造体に変換する
let goodsStructs = goods.compactMap { dict -> Goods? in
    if let name = dict["name"] as? String, let price = dict["price"] as? Int {
        return Goods(name: name, price: price)
    } else {
        return nil
    }
}
print(goodsStructs)

reduceを使った例

reduceメソッドは、配列の要素を連結(結合ともいう)するメソッド。このコードだと、苗字と名前の間に、スペースを入れて、配列の値を結合している。

let names = ["田中", "太郎", "佐藤", "二郎", "山田", "花子"]

// 苗字と名前の間に半角スペースを入れて連結する
let result = names.reduce("", { acc, name in
    acc + " " + name
})

print(result)// 田中 太郎 佐藤 二郎 山田 花子

参考にしたサイト

今回は、こちらのサイトを参考に学習しました。
昔お世話になった、日本語でSwiftの解説がされているサイト

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?