Back to Swift Reference Ask BeeAI
🗄️ SwiftDataBeginneriOS 17+ · macOS 14+
@Model & ModelContainer
Turn a Swift class into a persistent model and wire the storage into your app with one modifier.
The @Model macro makes a class persistable. Stored properties become columns; relationships to other models are inferred automatically.
Attach .modelContainer(for:) at the app level, then read the context with @Environment(\.modelContext) to insert and delete objects.
swiftdata-model.swift
1import SwiftData
2import SwiftUI
3
4@Model
5final class Habit {
6 var name: String
7 var createdAt: Date
8 @Relationship(deleteRule: .cascade) var entries: [HabitEntry] = []
9
10 init(name: String, createdAt: Date = .now) {
11 self.name = name
12 self.createdAt = createdAt
13 }
14}
15
16@Model
17final class HabitEntry {
18 var date: Date
19 init(date: Date = .now) { self.date = date }
20}
21
22@main
23struct HabitsApp: App {
24 var body: some Scene {
25 WindowGroup { ContentView() }
26 .modelContainer(for: Habit.self)
27 }
28}Common pitfalls
- @Model only works on classes, not structs.
- Changing a model after release needs a migration plan (VersionedSchema + SchemaMigrationPlan) for non-trivial changes.
Still unclear? Ask BeeAI about @Model & ModelContainer.
Get a tailored explanation, or paste your own code for a Swift 6 review. Free members get daily questions — Pro is unlimited.
Related topics
Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.
See Pro Plans