.onDelete not working in sorted ForEach - SwiftUI

Viewed 1490

I have no clue on why this is not working. I've always done it the same way, the only difference is the sorted method.

ForEach(userData.fruits_and_vegetables.sorted { $0.item < $1.item}) { grocery in
  DetailCardView(item: grocery.item, itemCount: grocery.count)
}.onDelete { (offset) in
  self.userData.fruits_and_vegetables.remove(atOffsets: offset)
}

Help! Thanks

2 Answers

You get offset of one array, but tries to apply it to another one... really won't work.

Instead it should be done, like

let sorted = userData.fruits_and_vegetables.sorted { $0.item < $1.item}

...

ForEach(sorted) { grocery in
  DetailCardView(item: grocery.item, itemCount: grocery.count)
}.onDelete { (offset) in
    for i in offset {
        if let found = self.userData.fruits_and_vegetables.firstIndex(where: { $0 == sorted[i] }) {
            self.userData.fruits_and_vegetables.remove(at: found)
        }
    }
}

and better move sorted and content of onDelete into your userData class.

I have the same problem. In remove function I add the same sort:

func remove(at offsets: IndexSet) {
    for index in offsets {
          let grocery = userData.fruits_and_vegetables.sorted { $0.item < $1.item }[index]
              grocery.delete // Your delete method
    }
}

In my code I also had a .filter, which I added there too. Everything works!

Related