hi,
i'm assuming you want to delete candies from a country, and not countries
first, you'll need to move the .onDelete modifier to the inner ForEach; and second, asking to perform a simple function by name doesn't work because it is passed only an IndexSet of offsets of candies -- but you really need to know which country those offsets apply to.
the solution is to use a closure inside the .onDelete modifier to intercept and then re-route those offsets to a deletion function that also knows the country for which the offsets apply. something like this should work:
List {
ForEach(countries, id: \.self) { country in
Section(header: Text(country.wrappedFullName)) {
ForEach(country.candyArray, id: \.self) { candy in
Text(candy.wrappedName)
}
.onDelete(perform: { offsets in
self.deleteCandies(at: offsets, from: country)
})
}
}
}
now you can do the deletion function this way. (note: the removeFromCandy() function is one of the accessors defined by XCode in generating the Country+CoreDataProperties.swift file.)
func deleteCandies(at offsets: IndexSet, from country: Country) {
for offset in offsets {
let candyToDelete = country.candyArray[offset]
country.removeFromCandy(candyToDelete)
moc.delete(candyToDelete)
}
if moc.hasChanges{
try? moc.save()
}
}
hope this helps,
DMG
*** added as an afterthought: this code works well if the IndexSet has only one entry. if there are situations where you have more than one entry, this may or may not do the right thing (depending on the order of entries in the IndexSet).
it might be safer to explicitly delete in reverse order of index so that deletions don't conflict with the indexing of the computed property candyArray. so you might want the deletion loop above to be written using
for offset in offsets.sorted().reversed() {
DMG