Mobile development · Intermediate · 25 min
Store data in a SwiftUI app with SwiftData
By Padding · Updated 18 Nov 2026
Swift 6.4 · Xcode 27.1 · iOS 27.1 SDK · macOS Tahoe 26.6
You will build a small shop stock app that saves suppliers and products on the iPhone with SwiftData, lists them with sorted and filtered queries, survives a schema change through a migration plan, and is checked by tests that run against an in-memory store.
On this page
Most apps need to keep something after the user closes them: a list of orders, a draft, a set of saved places. On Apple platforms, SwiftData is the framework for that. You describe your data as ordinary Swift classes, and SwiftData stores them in a database file on the device, loads them into your views and keeps the views up to date when the data changes.
In this tutorial you build Shelf, a stock app for a small shop. A shop owner adds suppliers, adds products under each supplier, sees which products are running low, and searches by name. All of it lives on the phone, so the app works with no network at all. That matters when the person using it is on prepaid data or in a market with weak signal. Then you change the data model after the app has shipped, the way real apps do, and write a migration plan so existing data survives. Last, you write tests against a database that lives only in memory.
You need Xcode 27.1, which includes Swift 6.4 and the iOS 27.1 SDK. SwiftData itself works on iOS 17 and later, so you can use it in apps that still support older phones. If @State and @Observable are new to you, read manage state in SwiftUI with @State, @Binding and @Observable first. SwiftData models behave much like @Observable classes, and that tutorial explains what that means.
Step 1 · Create the project and describe the data
In Xcode, choose File, New, Project, then the iOS App template. Name it Shelf, choose SwiftUI for the interface and Swift for the language, and set Storage to None. The SwiftData option would add a sample model for you. Here you write the model yourself, so you know what each line does. Set Testing System to Swift Testing with XCTest UI Tests, because you use the unit test target in the last step.
Add a Swift file named Models.swift and replace its contents with this:
import Foundation
import SwiftData
@Model
final class Supplier {
var name: String
var phone: String
@Relationship(deleteRule: .cascade, inverse: \Product.supplier)
var products: [Product] = []
init(name: String, phone: String) {
self.name = name
self.phone = phone
}
}
@Model
final class Product {
var name: String
var quantity: Int
var addedAt: Date
var supplier: Supplier?
init(name: String, quantity: Int, supplier: Supplier? = nil) {
self.name = name
self.quantity = quantity
self.addedAt = .now
self.supplier = supplier
}
}What each part does:
@Modelturns a class into something SwiftData can store. It adds the code that tracks changes to each property, and it makes the class observable, so a view that readsproduct.quantityredraws when the quantity changes. You do not add@Observableyourself.- Models must be classes, not structs. Two screens that show the same product share one object, so an edit on one screen appears on the other.
- Stored properties become columns.
String,Int,Date,Bool,Double,Data, optionals of these, andCodablestructs and enums all work. supplierandproductsare the two ends of one relationship. A product has at most one supplier, and a supplier has many products. Theinverse:argument tells SwiftData that both properties describe the same link, so settingproduct.supplieralso adds the product tosupplier.products.
Check it worked
Press Command-B. The project builds with no errors. If Xcode reports that @Model cannot be applied to a struct, or that a class has no initialiser, compare your file with the code above: every model must be a class (this tutorial marks them final) with an init that sets every property that has no default value.
Step 2 · Open the store with the modelContainer modifier
A model container is the database: it knows your models and owns the file on disk. A model context is the working area where you insert, change and delete objects before they are written to that file. SwiftUI sets up both for you with one modifier.
Open ShelfApp.swift and replace it with this:
import SwiftUI
import SwiftData
@main
struct ShelfApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: [Supplier.self, Product.self])
}
}.modelContainer(for:) creates a container for the listed models, stores it in the app's Application Support folder, and puts its main context into the SwiftUI environment. Every view inside the window can now reach the context. Listing Product is optional, because SwiftData follows relationships from Supplier and finds it anyway, but naming both makes the schema easy to read.
The main context saves on its own. It writes changes to disk shortly after they happen and when the app moves to the background, so in most screens you never call save(). You will call it yourself in tests, where you want the write to happen at a known moment.
Check it worked
Run the app on an iPhone simulator with Command-R. You still see the template's "Hello, world!" screen, with no errors in the debug console. If the console prints a message that the store failed to load, delete the app from the simulator and run again; that happens when an earlier experiment left a store with a different model in place.
Step 3 · Add and delete suppliers through the model context
Replace ContentView.swift with a supplier list that reads from the store and writes to it:
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query(sort: \Supplier.name) private var suppliers: [Supplier]
@State private var showingNewSupplier = false
var body: some View {
NavigationStack {
List {
ForEach(suppliers) { supplier in
NavigationLink(value: supplier) {
VStack(alignment: .leading) {
Text(supplier.name)
Text("\(supplier.products.count) products")
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
.onDelete(perform: deleteSuppliers)
}
.navigationTitle("Suppliers")
.navigationDestination(for: Supplier.self) { supplier in
SupplierDetailView(supplier: supplier)
}
.toolbar {
Button("Add supplier", systemImage: "plus") {
showingNewSupplier = true
}
}
.sheet(isPresented: $showingNewSupplier) {
NewSupplierView()
}
.overlay {
if suppliers.isEmpty {
ContentUnavailableView("No suppliers yet",
systemImage: "shippingbox",
description: Text("Tap + to add the first one."))
}
}
}
}
private func deleteSuppliers(at offsets: IndexSet) {
for index in offsets {
modelContext.delete(suppliers[index])
}
}
}
struct NewSupplierView: View {
@Environment(\.modelContext) private var modelContext
@Environment(\.dismiss) private var dismiss
@State private var name = ""
@State private var phone = ""
var body: some View {
NavigationStack {
Form {
TextField("Name", text: $name)
TextField("Phone", text: $phone)
.keyboardType(.phonePad)
}
.navigationTitle("New supplier")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
}
ToolbarItem(placement: .confirmationAction) {
Button("Save") {
let trimmed = name.trimmingCharacters(in: .whitespaces)
modelContext.insert(Supplier(name: trimmed, phone: phone))
dismiss()
}
.disabled(name.trimmingCharacters(in: .whitespaces).isEmpty)
}
}
}
}
}SupplierDetailView does not exist yet, so add a placeholder at the bottom of the same file. You replace it in the next step:
struct SupplierDetailView: View {
let supplier: Supplier
var body: some View {
Text(supplier.name)
}
}Three things carry the data:
@Environment(\.modelContext)reads the context that the container put into the environment.@Query(sort: \Supplier.name)fetches every supplier, sorted by name, and fetches again whenever the store changes. You never reload the list by hand.modelContext.insert(_:)adds a new object andmodelContext.delete(_:)removes one. Because the query watches the store, the list updates as soon as either call runs.
A model object can be a NavigationLink value because @Model classes are Hashable.
Check it worked
Run the app. The empty screen says "No suppliers yet". Tap +, add "Adeyemi Wholesale" and "Kano Grains", and both appear in alphabetical order. Swipe left on one and tap Delete; it disappears. Now stop the app in Xcode, run it again, and the supplier you kept is still there. That relaunch is the real test: the data came back from the file, not from memory.
Step 4 · Add products and query them with sort and filter
Replace the placeholder SupplierDetailView with a screen that lists a supplier's products and lets the owner add one or change its quantity:
struct SupplierDetailView: View {
@Environment(\.modelContext) private var modelContext
let supplier: Supplier
@State private var newName = ""
private var sortedProducts: [Product] {
supplier.products.sorted { $0.name < $1.name }
}
var body: some View {
List {
Section("Add a product") {
HStack {
TextField("Product name", text: $newName)
Button("Add") {
let product = Product(name: newName, quantity: 0, supplier: supplier)
modelContext.insert(product)
newName = ""
}
.disabled(newName.isEmpty)
}
}
Section("Products") {
ForEach(sortedProducts) { product in
Stepper("\(product.name): \(product.quantity)",
value: Bindable(product).quantity, in: 0...999)
}
.onDelete { offsets in
for index in offsets {
modelContext.delete(sortedProducts[index])
}
}
}
}
.navigationTitle(supplier.name)
}
}Bindable(product).quantity gives the stepper a binding into the model object. Changing it changes the stored value, and the main context saves it for you.
The supplier screen walks the relationship. For a screen across all products, use a query with a filter. Add this view to the same file. It shows every product with fewer than five left, lowest first:
struct LowStockView: View {
@Query(filter: #Predicate<Product> { $0.quantity < 5 },
sort: \Product.quantity)
private var lowStock: [Product]
var body: some View {
List(lowStock) { product in
LabeledContent(product.name,
value: "\(product.quantity) left")
}
.navigationTitle("Running low")
}
}#Predicate is checked by the compiler and turned into a database query, so SwiftData filters in SQLite instead of loading every product and filtering in Swift. Not every Swift expression can be translated, and only some mistakes are caught at build time. The macro rejects Swift syntax it cannot represent, so those fail the build. Other predicates compile but the SQLite store cannot run them, for example one that reads a computed or @Transient property or calls a method the store does not support. Those fail only when the query first runs: the fetch throws, or the app stops with an unsupported-predicate error. Run each new query once, on the screen or in a test, before you rely on it.
A filter often depends on something the user types. A @Query is fixed when the view is created, so put the query in a small child view and build it in that view's initialiser:
struct ProductSearchResults: View {
@Query private var products: [Product]
init(searchText: String) {
_products = Query(
filter: #Predicate<Product> { product in
searchText.isEmpty || product.name.localizedStandardContains(searchText)
},
sort: \Product.name
)
}
var body: some View {
List(products) { product in
LabeledContent(product.name,
value: product.supplier?.name ?? "No supplier")
}
}
}
struct SearchView: View {
@State private var searchText = ""
var body: some View {
ProductSearchResults(searchText: searchText)
.searchable(text: $searchText)
.navigationTitle("Search")
}
}When searchText changes, SwiftUI creates ProductSearchResults again with a new query. localizedStandardContains ignores case and accents, so a search for "garri" finds "Garri" and a search for "ogi" finds "Ògì". That matters when product names are typed in Yoruba, Hausa, French or any mix of them.
Last, give the owner a way to reach the two new screens. Add these two buttons inside the existing .toolbar in ContentView, after the + button:
NavigationLink("Running low") { LowStockView() }
NavigationLink("Search") { SearchView() }Check it worked
Run the app. Open a supplier, add "Garri 5 kg" and "Palm oil 1 L", and raise Palm oil to 12 with the stepper. Go back: the supplier row now says "2 products". Tap Running low and you see Garri with "0 left" but not Palm oil. Tap Search, type "PALM", and Palm oil appears with its supplier's name. Relaunch the app; the quantities are as you left them.
Step 5 · Choose what happens to related data on delete
Delete a supplier now and its products go with it, because the relationship uses deleteRule: .cascade. That is a decision, not a default, and the wrong choice loses data or leaves junk behind. SwiftData offers four rules:
.nullify(the default if you do not set one) keeps the products and sets theirsuppliertonil. Use it when the child makes sense on its own..cascadedeletes the products too. Use it when the child has no meaning without the parent, such as the lines of an order..denyrefuses to delete the supplier while it still has products. The save fails with an error, and your code must handle it..noActionleaves the products pointing at a supplier that no longer exists. You then clean up yourself. Avoid it unless you have a specific reason.
For Shelf, a shop owner who stops buying from a supplier still has those goods on the shelf. Deleting the stock count along with the supplier is the wrong behaviour. Change the relationship in Models.swift to nullify:
@Relationship(deleteRule: .nullify, inverse: \Product.supplier)
var products: [Product] = []Changing a delete rule does not change the shape of the stored data, so the existing store opens without a migration.
Check it worked
Run the app. Open a supplier that has products and note their names. Go back, swipe to delete that supplier, then open Search and leave the field empty. The products are still listed, and their supplier now shows "No supplier".
Step 6 · Version the schema and migrate without losing data
Once the app is on people's phones, every change to a model changes the database they already have. SwiftData can handle simple changes by itself, but as soon as you need more than one change, or a change that needs code, you want a record of each version and a plan for moving between them. Set that up now, before you need it.
Say the shop owner wants a reorder level for each product, so the low-stock screen can use a different limit per product. That adds a property. Start by freezing the current model as version 1. Create ShelfSchemaV1.swift and copy the two models into an enum, exactly as they are now:
import Foundation
import SwiftData
enum ShelfSchemaV1: VersionedSchema {
static let versionIdentifier = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type] {
[Supplier.self, Product.self]
}
@Model
final class Supplier {
var name: String
var phone: String
@Relationship(deleteRule: .nullify, inverse: \Product.supplier)
var products: [Product] = []
init(name: String, phone: String) {
self.name = name
self.phone = phone
}
}
@Model
final class Product {
var name: String
var quantity: Int
var addedAt: Date
var supplier: Supplier?
init(name: String, quantity: Int, supplier: Supplier? = nil) {
self.name = name
self.quantity = quantity
self.addedAt = .now
self.supplier = supplier
}
}
}The copy must match the shipped model property for property. SwiftData recognises an existing store by the shape of its schema, and if version 1 differs from what is on the phone, it cannot tell which version the store is.
Now replace the contents of Models.swift with version 2, which adds reorderLevel with a default value:
import Foundation
import SwiftData
enum ShelfSchemaV2: VersionedSchema {
static let versionIdentifier = Schema.Version(2, 0, 0)
static var models: [any PersistentModel.Type] {
[Supplier.self, Product.self]
}
@Model
final class Supplier {
var name: String
var phone: String
@Relationship(deleteRule: .nullify, inverse: \Product.supplier)
var products: [Product] = []
init(name: String, phone: String) {
self.name = name
self.phone = phone
}
}
@Model
final class Product {
var name: String
var quantity: Int
var reorderLevel: Int = 5
var addedAt: Date
var supplier: Supplier?
init(name: String, quantity: Int, reorderLevel: Int = 5, supplier: Supplier? = nil) {
self.name = name
self.quantity = quantity
self.reorderLevel = reorderLevel
self.addedAt = .now
self.supplier = supplier
}
}
}
typealias Supplier = ShelfSchemaV2.Supplier
typealias Product = ShelfSchemaV2.Product
enum ShelfMigrationPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[ShelfSchemaV1.self, ShelfSchemaV2.self]
}
static var stages: [MigrationStage] {
[.lightweight(fromVersion: ShelfSchemaV1.self, toVersion: ShelfSchemaV2.self)]
}
}The type aliases mean the rest of the app keeps writing Product and Supplier and always gets the newest version. When you add version 3, you point the aliases at it and add a stage.
A lightweight stage covers changes SwiftData can make on its own: adding a property that is optional or has a default, removing a property, renaming one with @Attribute(originalName:), or adding a model. If a change needs your code, such as splitting a full name into two fields or removing duplicates before making a field unique, use MigrationStage.custom(fromVersion:toVersion:willMigrate:didMigrate:), which gives you a model context before and after the schema changes.
Tell the app to open the store with the plan. Replace ShelfApp.swift:
import SwiftUI
import SwiftData
@main
struct ShelfApp: App {
let container: ModelContainer
init() {
do {
container = try ModelContainer(
for: Schema(versionedSchema: ShelfSchemaV2.self),
migrationPlan: ShelfMigrationPlan.self
)
} catch {
fatalError("Could not open the Shelf store: \(error)")
}
}
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(container)
}
}A crash on a failed store is acceptable while you develop, because it makes the problem impossible to miss. Before you ship, replace fatalError with a screen that explains the problem and keeps the file, so a failed migration never wipes a shop's stock list.
Finally, make the low-stock screen use the new field. In LowStockView, change the filter to compare two properties of the same product:
@Query(filter: #Predicate<Product> { $0.quantity < $0.reorderLevel },
sort: \Product.quantity)
private var lowStock: [Product]Check it worked
Do not delete the app from the simulator first; the point is to open the old store. Run the app. The suppliers and products you added in earlier steps are all still there. Open Running low: products with fewer than 5 left appear, because every existing product received the default reorder level of 5 during the migration. If the app crashes at launch with a message about an unknown model version, the V1 copy does not match the model you ran before; compare the two property by property.
Step 7 · Use in-memory containers for previews and tests
Previews and tests should never touch the real store. A container created with isStoredInMemoryOnly: true starts empty every time and disappears when the preview or test ends.
Add PreviewData.swift with a container that is filled with sample data:
import SwiftData
@MainActor
enum PreviewData {
static let container: ModelContainer = {
do {
let container = try ModelContainer(
for: Supplier.self, Product.self,
configurations: ModelConfiguration(isStoredInMemoryOnly: true)
)
let supplier = Supplier(name: "Adeyemi Wholesale", phone: "0800 000 0000")
container.mainContext.insert(supplier)
container.mainContext.insert(Product(name: "Garri 5 kg", quantity: 2, supplier: supplier))
container.mainContext.insert(Product(name: "Palm oil 1 L", quantity: 12, supplier: supplier))
return container
} catch {
fatalError("Could not create the preview container: \(error)")
}
}()
}Then add previews at the end of ContentView.swift:
#Preview("Suppliers") {
ContentView()
.modelContainer(PreviewData.container)
}
#Preview("Running low") {
NavigationStack { LowStockView() }
.modelContainer(PreviewData.container)
}For tests, open the file Xcode created in the ShelfTests target. Because you chose Swift Testing when you made the project, it already imports Testing; replace its contents with the tests below. Swift Testing creates a fresh instance of the test struct for every test, so each test gets its own in-memory container and tests cannot affect each other:
import Testing
import SwiftData
@testable import Shelf
@MainActor
struct ShelfStoreTests {
// Keep the container in a property. A context does not keep its
// container alive, so returning only mainContext from a helper
// lets the container be freed while the test still uses it.
let container: ModelContainer
init() throws {
container = try ModelContainer(
for: Supplier.self, Product.self,
configurations: ModelConfiguration(isStoredInMemoryOnly: true)
)
}
@Test func newProductsGetAReorderLevelOfFive() throws {
let context = container.mainContext
context.insert(Product(name: "Rice 10 kg", quantity: 3))
try context.save()
let products = try context.fetch(FetchDescriptor<Product>())
#expect(products.count == 1)
#expect(products.first?.reorderLevel == 5)
}
@Test func deletingASupplierKeepsItsProducts() throws {
let context = container.mainContext
let supplier = Supplier(name: "Kano Grains", phone: "0800 000 0001")
context.insert(supplier)
context.insert(Product(name: "Millet", quantity: 8, supplier: supplier))
try context.save()
context.delete(supplier)
try context.save()
let products = try context.fetch(FetchDescriptor<Product>())
#expect(products.count == 1)
#expect(products.first?.supplier == nil)
}
@Test func lowStockFilterUsesEachProductsReorderLevel() throws {
let context = container.mainContext
context.insert(Product(name: "Sugar", quantity: 4))
context.insert(Product(name: "Salt", quantity: 4, reorderLevel: 2))
try context.save()
let lowStock = FetchDescriptor<Product>(
predicate: #Predicate { $0.quantity < $0.reorderLevel }
)
let names = try context.fetch(lowStock).map(\.name)
#expect(names == ["Sugar"])
}
}The tests call save() before fetching, so the delete rule and the stored defaults run exactly as they do on a phone. The first test checks that a new product gets a reorder level of 5; it does not migrate a version 1 store, which you checked by hand in the previous step. The second test is the delete-rule decision from earlier, written down. If someone changes the rule back to .cascade, it fails.
Tests and previews run on the main actor here because a ModelContext is not safe to share between threads. For heavy work away from the main thread, such as importing a large price list, SwiftData provides the @ModelActor macro, which gives an actor its own context on the same container.
Check it worked
Open ContentView.swift and show the canvas with Option-Command-Return. The Suppliers preview shows Adeyemi Wholesale with "2 products", and the Running low preview shows Garri 5 kg. Press Command-U to run the tests. The Test navigator shows all three tests with green ticks. Change the delete rule in ShelfSchemaV2.Supplier to .cascade, press Command-U again, and deletingASupplierKeepsItsProducts fails. Change it back before you continue.
Step 8 · Decide when SwiftData is the wrong tool
SwiftData fits apps like Shelf well: one user, data on the device, SwiftUI screens. It is worth knowing where it stops, so you choose on purpose.
Core Data is still the better choice when:
- Your app must support iOS 16 or earlier. SwiftData needs iOS 17.
- You already have a large Core Data model and a team that knows it. SwiftData can share a store with Core Data, so you can move one part at a time instead of rewriting.
- You need the parts of Core Data that SwiftData does not expose, such as fine control over the persistent store coordinator or features of CloudKit beyond a single user's private database.
GRDB, an open-source SQLite library for Swift, is often the better choice when:
- You want to write SQL yourself, use SQLite features such as full-text search directly, or read the schema in plain SQL files.
- The same database schema must match one used by an Android app or a server, so the tables need exact names and types.
- You want value types (structs) instead of shared class instances, and explicit control over which thread reads and writes.
If you plan to sync with iCloud later, set that limit early. SwiftData syncs through CloudKit only when every property is optional or has a default, every relationship is optional, and no property uses @Attribute(.unique). Changing a model to meet those rules after shipping means another migration.
Check it worked
Write down, in one line each, your app's minimum iOS version, whether its data must match a schema outside the app, and whether it will sync. If the answers are "iOS 17 or later", "no" and "private iCloud at most", SwiftData is a sound choice. If any answer is different, read the matching paragraph above again before you commit to a framework.
Next steps
You now have an app that stores related data on the device, queries it with sorting and filtering, survives a schema change and has tests that check the delete rule, the default reorder level and the low-stock filter.
- To give Shelf a better layout, with sections, swipe actions and large-text support, see lay out SwiftUI screens with stacks, lists and NavigationStack.
- To build the same app for Android, read save data on Android with Room and DataStore. For a cross-platform version, read store data in a Flutter app with Drift.
Related tutorials
- Write end-to-end mobile tests with MaestroYou will have a small Maestro suite for a mobile app, with stable test IDs in React Native or Flutter, a shared sign-in flow fed by environment variables, smoke and full runs split by tags, and a CI job that runs the smoke flows on an Android emulator.
- Store data in a Flutter app with Drift and SQLiteYou will build a small shop credit book in Flutter 3.50 that keeps customers and what they owe in SQLite through Drift 2.35, with typed queries, a join, a list that redraws itself from a watch() stream, a tested schema migration and in-memory tests for all of it.
- Speed up a React Native app on a low-end Android phoneYou will measure a release build of your Expo app on a 2 to 3 GB Android phone, fix slow startup, dropped frames and re-render storms, and finish with a written performance budget you can check before every release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials