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. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.
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.
Learn Swift with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 122
- Lessons
- 409
Frequently Asked Questions
Is the “SwiftData @Model and ModelContext” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “SwiftData @Model and ModelContext”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.
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