tezvyn:

SwiftData

AI-drafted, machine-checkedSource: developer.apple.comintermediate
SwiftData

SwiftData is Apple's Swift native persistence framework, introduced in 2023 as a modern layer over the same storage engine Core Data uses. You declare models with the Model macro instead of a visual schema editor, and SwiftUI views stay in sync automatically.

WHY IT EXISTS Core Data has powered iOS persistence for over a decade, but it predates Swift and it shows: NSManagedObject subclasses, a separate visual schema editor, and NSFetchRequest APIs feel bolted onto a language with strong typing and macros. SwiftData exists to give developers Core Data's proven storage engine, including migrations and iCloud sync, through an API that looks and feels like ordinary Swift code.

THE MENTAL MODEL Think of SwiftData as Core Data wearing a Swift shaped costume. Underneath, the same battle tested SQLite backed engine does the storing, migrating, and syncing. What changes is the surface: a schema is just a class with an @Model attribute instead of a separate file, and queries are Swift property wrappers instead of a fetch request builder.

HOW IT WORKS You mark a class with the @Model macro, which generates conformance to PersistentModel and rewrites stored properties to route through SwiftData's storage layer at compile time. A ModelContainer is created for a schema, usually once at app launch, and holds the actual store. A ModelContext, injected into SwiftUI's environment, tracks inserts, updates, and deletes, saving them either automatically or with an explicit call. Inside a view, the @Query property wrapper runs a fetch descriptor and keeps its results live, so the view redraws when matching data changes, mirroring how an observable object drives updates elsewhere in SwiftUI.

WHEN IT MATTERS It matters when choosing how a new app persists structured data locally. SwiftData is the simpler choice for straightforward models and standard SwiftUI apps, cutting significant boilerplate versus Core Data. The footgun is assuming full feature parity: complex Core Data setups, like custom migrations with heavy data transformation logic or several configurations sharing one store, still sometimes need Core Data directly, and SwiftData's minimum deployment target of iOS 17 rules it out for apps supporting older devices.

ONE CONCRETE EXAMPLE A recipe app defines an @Model class Recipe with a title, an ingredients array, and a relationship to a Category model. In a SwiftUI list view, @Query private var recipes: [Recipe] fetches and observes all recipes with no manual fetch request, and calling modelContext.insert on a new recipe immediately updates the list on screen.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.