I am trying to simply delete an element from a list in Swift and SwiftUI. Without binding something in the ForEach loop, it does get removed. However, with binding something it crashes with an error Index out of range. It seems like the ForEach loop is constant, not updating, and trying to render at the specific index.
Example view code:
@ObservedObject var todoViewModel: TodoViewModel
//...
ForEach(self.todoViewModel.todos.indices) { index in
TextField("Test", text: self.$todoViewModel.todos[index].title)
.contextMenu(ContextMenu(menuItems: {
VStack {
Button(action: {
self.todoViewModel.deleteAt(index)
}, label: {
Label("Delete", systemImage: "trash")
})
}
}))
}
Example view model code:
final class TodoViewModel: ObservableObject {
@Published var todos: [Todo] = []
func deleteAt(_ index: Int) -> Void {
self.todos.remove(at: index)
}
}
Example model code:
struct Todo: Identifiable {
var id: Int
var title: String = ""
}
Does anyone know how to properly delete an element from a list where it is bound in a ForEach loop?