NEW: Learn to build the incredible iOS 15 Weather app today! >>

Delete from CoreData

Forums > Videos

I just follow this Paul video about CoreData and i'm trying to implement the deletion of an element using .onDelete explained in this article. The problem is no matter which row i swipe, this action always remove the first element in the list . Can anyone help me?

import SwiftUI

struct ContentView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Country.entity(), sortDescriptors: []) var countries: FetchedResults<Country>

    var body: some View {
            VStack {
                List {
                    ForEach(countries, id: \.self) { country in
                        Section(header: Text(country.wrappedFullName)) {
                            ForEach(country.candyArray, id: \.self) { candy in
                    .onDelete(perform: removeCountry)

                Button("Add") {
                    let candy1 = Candy(context: self.moc)
           = "Mars"
                    candy1.origin = Country(context: self.moc)
                    candy1.origin?.shortName = "UK"
                    candy1.origin?.fullName = "United Kingdom"

                    let candy2 = Candy(context: self.moc)
           = "KitKat"
                    candy2.origin = Country(context: self.moc)
                    candy2.origin?.shortName = "UK"
                    candy2.origin?.fullName = "United Kingdom"

                    let candy3 = Candy(context: self.moc)
           = "Twix"
                    candy3.origin = Country(context: self.moc)
                    candy3.origin?.shortName = "UK"
                    candy3.origin?.fullName = "United Kingdom"

                    let candy4 = Candy(context: self.moc)
           = "Toblerone"
                    candy4.origin = Country(context: self.moc)
                    candy4.origin?.shortName = "CH"
                    candy4.origin?.fullName = "Switzerland"


    func removeCountry(at offSets: IndexSet) {
        for index in offSets {
            let country = countries[index]


Hacking with Swift is sponsored by Essential Developer

SPONSORED Only until this Sunday, December 12th, you can join a free crash course to learn advanced techniques for testing new and legacy Swift code — it's the fast track to becoming a complete Senior iOS Developer!

Click to learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.