GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Proyect 11: deleting from a swiftData query

Forums > 100 Days of SwiftUI

I am trying this code:

func deleteBooks (at offsets: IndexSet) {
        for offset in offsets {
            // find this book in my query
            let book = books[offset]
            // delete it from the context
            modelContext.delete(book)
        }
    }

It works perfect with:

 .onDelete(perform: deleteBooks) 

But what if I create a button to delete a book that is inside a list? how have I got to call that funcion???

Button ("Delete") {
deleteBooks(at: ??????????????????)
}

how have I got to call that function to make it work????

Sorry if it is a really easy or silly question, but I don't now how to call it...

   

Do you mean adding a button of your own, not the one provided by native API, aka swipe to delete?

If so, you may create a button inside a list itself. Similar to below:

Button(action: {
  removeBook(book: book)
}, label: {
  Image(systemName: "trash")
)
.buttonStlye(.plain)

and function will be something like:

func removeBook(book: Book) {
  modelContext.delete(book)
}

   

It works !!! Thanks a lot!

So, this kind of function

func deleteBooks (at offsets: IndexSet) {
        for offset in offsets {
            // find this book in my query
            let book = books[offset]
            // delete it from the context
            modelContext.delete(book)
        }
    }

is needed when I want to delete a book in a list using .ondelete , isn't it?

   

Mark It !

If you're happy with a solution, please mark your question as "Solved".

Since you created this forum thread, only you can mark the thread as "Solved"

1      

is needed when I want to delete a book in a list using .ondelete , isn't it?

That's correct!

   

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. This Black Friday, unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a free crash course.

Save your spot

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.