UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: I can't figure out how to get the correct "task" when using onDelete. I need to delete it from CoreData.

Forums > SwiftUI

List {
    ForEach(tasks) { task in
        HStack {
            Text("\(task.name)")
            Spacer()
            Button(action: {
                let newStatus: Bool = !task.isComplete
                viewContext.performAndWait {
                    task.isComplete = newStatus
                    try? viewContext.save()
                }
                var completeTasks = 0
                tasks.forEach { task in
                    if task.isComplete {
                        completeTasks += 1
                    }
                }
                scores.forEach { score in
                    if Calendar.current.isDateInToday(score.date) {
                        var newStatus: Int32 = 100
                        if tasks.count > 0 {
                            newStatus = Int32(ceil(100.0/(Double(tasks.count))) * Double(completeTasks) > 100 ? 100 : ceil(100.0/Double(tasks.count)) * Double(completeTasks))
                        }
                        viewContext.performAndWait {
                            score.score = newStatus
                            try? viewContext.save()
                        }
                    }
                }
            }) {
                if task.isComplete {
                    Image(systemName: "checkmark.circle.fill")
                }
                else {
                    Image(systemName: "checkmark.circle")
                }
            }
        }
    }
    .onDelete(perform: { indexSet in
        viewContext.delete(task)
        do {
            try viewContext.save()
        } catch {
            print(error)
        }
    })
}

2      

hi,

the indexSet parameter passed in with the .onDelete modifier provides indices into the tasks array that drives the ForEach for the items to be deleted. (i assume it's an array, but it could be anything that conforms to RandomAccessCollection.)

you should then be able to do something like this:

for index in indexSet {
    viewContext.delete(tasks[index])
}

hope that helps,

DMG

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.