Skip to main content

How to delete all instances of a particular model

About 1 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftswiftdataxcodeappstore

How to delete all instances of a particular model 관련

SwiftData by Example

Back to Home

How to delete all instances of a particular model | SwiftData by Example

How to delete all instances of a particular model

Updated for Xcode 15

SwiftData’s ModelContext class has a dedicated delete(model:) method that removes from your context all instances of a particular model. Once a save is triggered, either manually or using autosave, the objects will be deleted from disk too.

For example, if we had a Student model we could delete all its instances like this:

do {
    try modelContext.delete(model: Student.self)
} catch {
    print("Failed to delete students.")
}

If you want only some of your model instances to be deleted, provide a predicate to the where parameter like this. For example, if we wanted to delete all schools that don’t have any active students, we’d write this:

try modelContext.delete(model: School.self, where: #Predicate { $0.students.isEmpty })

Tips

Technically the delete(model:) method has an overload that allows an includeSubclasses Boolean to be passed in. As far as I can tell this is impossible to use, because SwiftData models cannot be subclassed at the time of writing.


이찬희 (MarkiiimarK)
Never Stop Learning.