LoginSignup
2
1

【SwiftUI】順番付きで重複のないリストの作り方

Last updated at Posted at 2023-07-27

はじめに

SwiftUIでアプリを開発していて、重複のないリストを作りたいと思いました。

まず、重複のないデータを扱うためにSetを使うことを考えました。しかし、Setは順番を保持しないため私の目的には合いませんでした。

そこで、Appleが公開しているライブラリ「OrderedCollections」を使うことにしました。このライブラリをインポートすると、重複がなく順番を保持できるOrderedSetという型を使用できます。これを使えば、私の目的を達成できそうです。

手順

1. ライブラリをインストールする

File > Add Packages...を選択
スクリーンショット 2023-07-27 20.24.54.png

Apple Swift Packagesにあるswift-collectionsを選択
スクリーンショット 2023-07-27 20.25.03.png

OrderedCollectionsにチェックを入れてAdd Package
スクリーンショット 2023-07-27 20.25.56.png

2. コードを書く

コード全体

import SwiftUI

// OrderedCollectionsをインポート
import OrderedCollections

struct ContentView: View {

    // OrderedSetを使う
    @State private var people: OrderedSet<String> = [
        "ジョブズ",
        "ウォズ",
        "クック",
        "ジョニー",
        "ジョン",
        "エディ",
        "フィル",
        "クレイグ",
        "アンジェラ"
    ]
    
    var body: some View {
        NavigationStack {
            List {

                // 重複がないのでidに.selfを指定してもバグが起きない
                ForEach(people, id: \.self) { person in
                    HStack {
                        Text(person)
                        Spacer()
                        Button {
                            people.remove(person)
                        } label: {
                            Image(systemName: "minus.circle.fill")
                                .symbolRenderingMode(.palette)
                                .foregroundStyle(.white,.red)
                        }
                        .buttonStyle(.plain)
                    }
                }
            }
            .animation(.easeInOut, value: people)
            .toolbar {
                Button {

                    // すでにpeopleに"ジョブズ"が入っていると追加できない
                    // "ジョブズ"を削除すると追加できる
                    people.append("ジョブズ")
                } label: {
                    Image(systemName: "plus")
                }
            }
        }
    }
}

このコードを実行すると、最初はプラスボタンを押しても何も起きません。しかし、"ジョブズ"を削除してからプラスボタンを押すと"ジョブズ"が追加されます。OrderedSetがうまく機能していることがわかります。

おわりに

SwiftUIで重複のないリストを作る方法を紹介しました。この記事が参考になったという方は、いいねとフォローよろしくお願いします。

参考文献

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