Overview
- Successor to Core Data - Modern persistence framework from Apple
- Built with SwiftUI in mind - Seamless integration with SwiftUI's declarative syntax
- Auto-save by default - Changes are automatically persisted without explicit save calls
Core Concepts
Model Container & Context
- Container: Manages the persistent storage (the database)
- Context: Working space where you perform CRUD operations
- Flow: Work with context → Save changes → Persisted in container
// Setup in App file
.modelContainer(for: [Expense.self])
The @Model Macro
Marks a class as a SwiftData model and automatically generates:
- Persistence logic
- Observable properties
- Change tracking
- Relationship management
@Model
class Expense {
var name: String
var date: Date
var value: Double
init(name: String, date: Date, value: Double) {
self.name = name
self.date = date
self.value = value
}
}