Is it possible to delete an item from Coredata using onTapGesture?

I know about .onDelete modifier, but say I want to remove an item from Coredata using onTapGesture is that possible?

Code Block         
 .onDelete { indexSet in
          let deleteItem = self.isFavorite[indexSet.first!]
          self.managedObjectContext.delete(deleteItem)
          do {
            try self.managedObjectContext.save()
          }catch {
            print(error)
          }
        }


I tried doing

Code Block
         .onTapGesture { indexSet in
          let deleteItem = self.isFavorite[indexSet.first!]
          self.managedObjectContext.delete(deleteItem)
          do {
            try self.managedObjectContext.save()
          }catch {
            print(error)
          }
        }

But that didn't go well.
hi,

the .onDelete modifier is usually something you add to a ForEach, as in

Code Block
List {
ForEach(items) { item in
Text(item.name)
}
.onDelete(perform: yourDeleteFunction)
}


the .onTapGesture is something you would add to a view associated with an item in the list, within the scope of the ForEach:

Code Block
List {
ForEach(items) { item in
Text(item.name)
.onTapGesture({ doSomething(to: item) }) // doSomething could certainly delete this item
}
}


(i think that's right and) hope that helps,
DMG
Thanks, this sort of helps. I sort of knew the difference between the two, but struggling to know the proper index in coredata.
So here's where I'm getting hung up. I created a function in the view and then call removeFavorite, but the compiler fails.

Code Block
@Environment(\.managedObjectContext) var managedObjectContext
 @FetchRequest(fetchRequest: FavoriteItem.getAllFavorites()) var favorites:FetchedResults<FavoriteItem>
  func removeFavorite(at offsets: IndexSet) {
    for item in offsets {
      let favorite = favorites[item]
      managedObjectContext.delete(favorite)
    }
  }


Code Block
                   Text("Foo")
                    .onTapGesture(perform: removeFavorite)

I think you want your onTapGesture more like this where it’s directly deleting the item from the ForEach.
Code Block Swift
List {
ForEach(0 ..< items.count) { index in
Text(items[index].name)
.onTapGesture {
let favorite = favorites[index]
managedObjectContext.delete(favorite)
}
}
}

Is it possible to delete an item from Coredata using onTapGesture?
 
 
Q