SwiftData @Model and ModelContext
Defining models with @Model macro and performing CRUD via ModelContext.
SwiftData @Model and ModelContext is a free Swift Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
SwiftData Introduction
SwiftData (iOS 17+) is Apple's modern, Swift-native persistence framework built on Core Data under the hood.
import SwiftData
// Main concepts: @Model, ModelContainer, ModelContext@Model Macro
Annotate a class with @Model to make it a persistable SwiftData model. Properties become stored attributes automatically.
@Model
class Item {
var name: String
var createdAt: Date
init(name: String) {
self.name = name
self.createdAt = Date()
}
}ModelContainer Setup
Create a ModelContainer with your model types and inject it into SwiftUI's environment.
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: Item.self)
}
}ModelContext in Views
Use @Environment(\.modelContext) to access the model context in a SwiftUI view.
struct AddItemView: View {
@Environment(\.modelContext) private var context
func addItem() {
context.insert(Item(name: "New Item"))
}
}Inserting and Deleting
Call context.insert to add and context.delete to remove models. Changes auto-save by default.
let item = Item(name: "Coffee")
context.insert(item) // add
context.delete(item) // remove
// Auto-saved on next run loop@Query for Fetching
@Query in SwiftUI views automatically fetches and updates when the underlying data changes.
struct ItemList: View {
@Query(sort: \Item.createdAt, order: .reverse) var items: [Item]
var body: some View {
List(items) { item in Text(item.name) }
}
}Filtering with Predicates
Pass a #Predicate to @Query to filter results declaratively.
@Query(filter: #Predicate<Item> { $0.name.contains("Swift") })
var swiftItems: [Item]Manual Save
Call try context.save() when you need explicit control over when changes are persisted.
do {
try context.save()
} catch {
print("Save error: \(error)")
}@Attribute for Customization
Use @Attribute on properties to customize persistence behavior (e.g., unique, external storage).
@Model
class User {
@Attribute(.unique) var email: String
@Attribute(.externalStorage) var avatar: Data?
init(email: String) { self.email = email }
}@Transient Properties
Mark properties with @Transient to exclude them from persistence.
@Model
class Session {
var token: String
@Transient var isExpired: Bool = false
init(token: String) { self.token = token }
}ModelContainer Configuration
Configure the container with an explicit schema and migration plan for versioned models.
let schema = Schema([Item.self, User.self])
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
let container = try ModelContainer(for: schema, configurations: config)Quick Check
Which SwiftUI property wrapper automatically fetches SwiftData models and updates the view when data changes?
Lesson Recap
Annotate classes with @Model to make them persistable. Set up ModelContainer at the app level. Read/write via @Environment(\.modelContext). Fetch reactively with @Query. Filter with #Predicate.
Frequently asked questions
Is the “SwiftData @Model and ModelContext” lesson free?
Yes — the full text of “SwiftData @Model and ModelContext” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “SwiftData @Model and ModelContext”?
Defining models with @Model macro and performing CRUD via ModelContext. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “SwiftData @Model and ModelContext” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Core Data Stack: NSPersistentContainer Setup
- SwiftData @Model and ModelContext
- Relationships and Fetch Descriptors
- Lightweight Migrations and CloudKit Sync