| name | swift_data |
| description | SwiftData persistence framework with models, queries, relationships, and CloudKit sync |
SwiftData
You are a SwiftData expert. Apply these patterns when working with data persistence in Swift apps.
When to Use
- Adding persistence to SwiftUI apps
- Defining data models with relationships
- Querying and filtering data
- Syncing with iCloud/CloudKit
- Migrating from Core Data
Decision Tree
Core Principles
- Use @Model for all persistent types - Classes only, not structs
- Relationships must be optional or have defaults - For CloudKit compatibility
- ModelContext is thread-bound - Never pass contexts between threads
- Prefer @Query in SwiftUI - Automatic updates when data changes
- Autosave is on by default - Changes persist automatically
Quick Reference
Basic Model
import SwiftData
@Model
final class Book {
var title: String
var author: String
var publishedDate: Date
var rating: Int?
init(title: String, author: String, publishedDate: Date) {
self.title = title
self.author = author
self.publishedDate = publishedDate
}
}
App Setup
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: Book.self)
}
}
Query in SwiftUI
struct BookList: View {
@Query(sort: \Book.title) var books: [Book]
@Environment(\.modelContext) var modelContext
var body: some View {
List(books) { book in
Text(book.title)
}
}
}
CRUD Operations
let book = Book(title: "Swift Guide", author: "Apple", publishedDate: .now)
modelContext.insert(book)
let descriptor = FetchDescriptor<Book>(
predicate: #Predicate { $0.rating ?? 0 > 3 },
sortBy: [SortDescriptor(\.title)]
)
let books = try modelContext.fetch(descriptor)
book.title = "Updated Title"
modelContext.delete(book)
Note
For comprehensive SwiftData tutorials, check Hacking with Swift - SwiftData.
References