7
4

More than 5 years have passed since last update.

【Swift4】メソッド一発で配列をグルーピング

Last updated at Posted at 2018-09-07

Dictionary.init(grouping:by:) を使って簡単なデモ

Swift4から新しく追加された関数で、TableViewで表示されている内容を任意の条件でグルーピングして表示したい時にかなり使えます!

関数の説明(ざっくり)

説明しなくてもいいからリファレンス見せろって人はこちらにリンク貼っておきます
ざっくり説明すると、groupingの後に同じ型の配列を引数として与え、byの後はグルーピンしたい要素を引数として与えると、グルーピングされた辞書が返ってきます。

実装

大学の授業という構造体を作りグルーピング

groupingExample.swift

//授業を構造体で定義します
//難易度をDifficultyという列挙型で定義します
struct Lesson {
    let name: String
    let credit: Int
    let difficulty: Difficulty

    enum Difficulty: Hashable {
        case A,B,C,D
    }
}

//授業型の配列を作成します
var lessonList: [Lesson] = [Lesson.init(name: "統計学", credit: 1, difficulty: .B),
                        Lesson.init(name: "会計学", credit: 2, difficulty: .C),
                        Lesson.init(name: "微分", credit: 2, difficulty: .A),
                        Lesson.init(name: "マクロ経済学", credit: 2, difficulty: .B),
                        Lesson.init(name: "ミクロ経済学", credit: 2, difficulty: .C),
                        Lesson.init(name: "英語", credit: 2, difficulty: .D),
                        Lesson.init(name: "積分", credit: 2, difficulty: .B),
                        Lesson.init(name: "線形代数", credit: 2, difficulty: .B),
                        Lesson.init(name: "中国語", credit: 2, difficulty: .C),
                        Lesson.init(name: "社会学", credit: 2, difficulty: .C)]

// 授業型の任意のプロパティを指定して、プロパティの値毎にグルーピングした辞書を返します
let groupedDicationary = Dictionary.init(grouping: lessonList, by: { (lesson) -> Lesson.Difficulty  in
    return lesson.difficulty
})

次回は上記のコードを使いながらTableViewで実装してみたいと思います!

7
4
2

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
7
4