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()
}
}