BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

Deleting from a SwiftData query

Paul Hudson    @twostraws   

We already used @Query to place SwiftData objects into a SwiftUI List, and with only a little more work we can enable both swipe to delete and a dedicated Edit/Done button.

Just as with regular arrays of data, most of the work is done by attaching an onDelete(perform:) modifier to ForEach, but rather than just removing items from an array we instead need to find the requested object in our query then use it to call delete() on our model context. Once all the objects are deleted, SwiftData's autosave system will kick in and apply the changes permanently.

So, start by adding this method to ContentView:

func deleteBooks(at offsets: IndexSet) {
    for offset in offsets {
        // find this book in our query
        let book = books[offset]

        // delete it from the context

We can trigger that by adding an onDelete(perform:) modifier to the ForEach of ContentView, but remember: it needs to go on the ForEach and not the List.

Add this modifier now:

.onDelete(perform: deleteBooks)

That gets us swipe to delete, and we can go one better by adding an Edit/Done button too. Find the toolbar() modifier in ContentView, and add another ToolbarItem:

ToolbarItem(placement: .topBarLeading) {

That completes ContentView, so try running the app – you should be able to add and delete books freely now, and can delete by using swipe to delete or using the edit button.

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.