Thursday, December 18, 2025

Batch Delete in SwiftData

Fatbobman:

SwiftData provides a batch deletion API that is more modern and type-safe than its Core Data counterpart.

[…]

Note: Unlike the standard single-object deletion modelContext.delete(_ model: T), batch deletion is only applied to the database after save() is executed.

Coming from Core Data, this is really strange. With Core Data, NSBatchUpdateRequest and the other batch operations are completely separate from saving the context. This makes sense because they operate directly on the database rather than on the in-memory objects that are owned by the context.

I’m trying to wrap my head around what SwiftData is even doing that batch deletions happen on save. Is it queuing up a bunch of SQL to be executed along with the save? Why would anyone want this?

Going by what the documentation literally says, with it taking place after the save, it sounds like it even reorders operations. If I do a batch delete, then insert some objects, then save, will it delete the new objects (if they match the predicate) even though I intended the insert to happen after clearing out the old objects? Or does executing the batch delete eagerly fetch the IDs of the objects to be deleted and then it deletes them by ID later (when the predicate might no longer match)?

Either way, it seems confusing in the event that there are multiple batch deletes in sequence. The first one might affect which objects match the predicate of the second one.

Although Swift 6 and iOS 26 have brought many improvements, as of now, SwiftData natively supports only batch deletion. It does not yet provide native APIs for Batch Update or Batch Insert.

Previously:

Comments RSS · Twitter · Mastodon

Leave a Comment