1
1

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.

【SwiftUI】ListでForEachを回すときの注意点

Last updated at Posted at 2020-08-15

#はじめに
SwiftUI のListで削除メソッドを作るときにアイテムを削除すると、ForEachで回していたUIコンポーネンツがIndex out of range のエラーを吐き出したので治し方を共有しておきます

##問題のコード

struct someView: View {
    @State var animals: [String] = ["🐶", "🐱", "🐊"]
    var body: some View {
        List {
            ForEach(0..<animals.count) { i in
                HStack {
                    Text(self.animals[i])
                        .padding(.all)
                    Spacer()
                }
            }
            .onDelete(perform: delete)
        }
    }

    func delete(at offsets: IndexSet) {
        animals.remove(atOffsets: offsets)
    }
}

この時、左スワイプで列を削除すると、必ずanimals[i]が範囲外になってしまうんです…
これは0..<animals.countが読み込まれた段階で判定されており、Binding要素ではないからだそうで。
参考

##解決法
ダイナミックに変更するにはidを指定すると良いとのこと

struct someView: View {
    @State var animals: [String] = ["🐶", "🐱", "🐊"]
    var body: some View {
        List {
            // id:\.self を指定する
            ForEach(animals, id: \.self) { animal in
                HStack {
                    Text(animal)
                        .padding(.all)
                    Spacer()
                }
            }
            .onDelete(perform: delete)
        }
    }

    func delete(at offsets: IndexSet) {
        animals.remove(atOffsets: offsets)
    }
}
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?