I have a ScrollView which displays a list of rows using a ForEach loop from an array. When I delete an item from the array, I get the error: Index out of range.
ScrollView {
ForEach(viewModel.tasks.indices, id: \.self){ index in
TaskRow(
task: self.$viewModel.tasks[index],
deleteAction: {
self.viewModel.deleteTask(task: self.viewModel.tasks[index])
}
)
}
}
This error only started occurring when I switched to passing the index from the ForEach loop instead of the 'task' itself. I had to do this so I could use a @Binding var task: Task in the subview: "TaskRow"
The 'delete action' is triggered by a button in the subview.
viewModel.deleteTask works as follows (using a dataManager):
final class StackDetailViewModel: ObservableObject {
@Published var tasks = [Task]()
var dataManager: DataManagerProtocol
init(dataManager: DataManagerProtocol = DataManager.shared){
self.dataManager = dataManager
fetchTasks()
}
}
extension StackDetailViewModel {
func fetchTasks() {
tasks = dataManager.fetchTasks()
}
func deleteTask(task: Task) {
dataManager.deleteTask(task: task)
fetchTasks()
}
}
Where the dataManager does this:
Class DataManager {
...
private var tasks = [Task]()
...
func fetchTasks() -> [Task] {
tasks
}
func deleteTask(task: Task) {
if let index = tasks.firstIndex(where: { $0.id == task.id }) {
tasks.remove(at: index)
}
}
}
I use protocols in my app but I've removed them here for simplicity. Any help would be greatly appreciated.
viewModel.deleteTask? - New DevDataManagerand yourViewModel. - New DevForEach(viewModel.tasks){ task into what I have shown above. Keeping the dataManager and ViewModel the same. - santi.gs