0

I have the following code and I'm getting a crash when I try to delete the row.

Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444
2020-10-02 17:08:37.983723-0400 HapticFactory[4201:213536] Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444

What can I do to fix this? Or do I have to approach this problem another way?

Code:

import SwiftUI

struct Tag: Identifiable {
    var id = UUID()
    var value: String = "ColorBlue"
    var color: Color = .blue
}

class ItemsViewModel: ObservableObject {
    @Published var tags: [Tag] = []
    
    func addTag(tag: Tag) {
        tags.append(tag)
    }
}

struct ContentView: View {
    @ObservedObject var viewModel = ItemsViewModel()
    
    var body: some View {
        List {
            ForEach(self.viewModel.tags.indices, id: \.self) { index in
                ColorPicker(selection: self.$viewModel.tags[index].color) {
                    TextField("", text: self.$viewModel.tags[index].value)
                }
            }.onDelete(perform: self.deleteRow)
            Button(action: { self.viewModel.addTag(tag: Tag()) }, label: {
                Text("Add Tag")
            })
        }
    }
    
    private func deleteRow(at indexSet: IndexSet) {
        self.viewModel.tags.remove(atOffsets: indexSet)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
visc
  • 4,794
  • 6
  • 32
  • 58
  • 1
    Does this answer your question? [Deleting list elements from SwiftUI's List](https://stackoverflow.com/questions/63079221/deleting-list-elements-from-swiftuis-list) – New Dev Oct 02 '20 at 21:23
  • @NewDev It's still not working using this solution https://stackoverflow.com/a/63080065/4102299. Also I can only apply onDelete to a ForEach.. that enables the swipe to delete – visc Oct 02 '20 at 21:34
  • Try this solution: https://stackoverflow.com/a/63083658/968155 ... and it's should, in principle, work with ForEach – New Dev Oct 02 '20 at 21:35
  • 1
    @NewDev I got it working. Thanks – visc Oct 02 '20 at 21:55
  • @NewDav you and Aspri say the issue was fixed in SeiftUI 2.0?? I’m running XCode 12 on Big Sur.. do I need this solution if it’s supposed to be fixed? – visc Oct 02 '20 at 22:41
  • I think even on 12, in some cases, it was failing for me. Can't remember now – New Dev Oct 02 '20 at 22:44

0 Answers0