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

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!

   

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, 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!

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.