NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Core Data delete functionality in Multiplatform swiftUI app

Forums > SwiftUI



I am building a multiplatform app that uses core data. I want to add some delete functionality.

When I created the project, apple provided some basic functionality which works for iOS, but not for mac. For deletion on iOS, you would use the .onDelete(perform:) modifier. When I pass in that method that takes in a IndexSet, the modifier passes the indexSet automatically to the method. This is the delete function:

private func deleteItems(offsets: IndexSet) {
        withAnimation {
   { items[$0] }.forEach(viewContext.delete)

            do {
            } catch {

This way of deleting works great on iOS, but MacOS doesn’t have that modifier. It has the onDeleteCommand(perform:) modifier. That modifier triggers a function when the users selects an item, and goes to the menu bar, and selects edit > delete. But, as that modifer doesnt pass in a IndexSet automatically like the onDelete modifier, this doesn’t work.

Is there a way of of getting the indexSet into a (state) variable that will be updated when a user selects an item, which I then could pass into the method when calling the .onDeleteModifier ?


Hey @BSM, not sure if you're still looking to solve this, but SwiftUI's .onDelete() modifier is available on macOS (on Big Sur, at least). It's triggered by swiping on your trackpad, though, so it's effectively non-discoverable.

What I do in WriteFreely (also a multiplatform SwiftUI app) is use a @Published property in an ObservableObject to track what the currently selected post is, and use that in .onDeleteCommand() (see here on GitHub).

Does something like that work for your codebase?


Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.