SwiftData helps your app save and load data easily. It keeps your information safe even when the app closes.
SwiftData setup (modern persistence) in iOS Swift
import SwiftData @Model class Item { var name: String init(name: String) { self.name = name } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: [Item.self]) } } }
The @Model attribute marks a class as data you want to save.
The .modelContainer(for:) modifier sets up storage for your data models.
import SwiftData @Model class Task { var title: String var done: Bool = false init(title: String) { self.title = title } }
import SwiftUI import SwiftData @main struct MyApp: App { var body: some Scene { WindowGroup { TaskListView() .modelContainer(for: [Task.self]) } } }
This app lets you add notes and saves them using SwiftData. Notes stay saved even if you close the app.
import SwiftUI import SwiftData @Model class Note { var content: String init(content: String) { self.content = content } } struct ContentView: View { @Environment(\.modelContext) private var context @Query private var notes: [Note] @State private var newNote = "" var body: some View { VStack { TextField("Enter note", text: $newNote) .textFieldStyle(.roundedBorder) .padding() Button("Add Note") { let note = Note(content: newNote) context.insert(note) try? context.save() newNote = "" } List(notes, id: \.self) { note in Text(note.content) } } .padding() } } @main struct NotesApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: [Note.self]) } } }
Always call try? context.save() after inserting or changing data to keep it saved.
Use @Query to automatically get updated data from your storage.
SwiftData works well with SwiftUI and updates your UI when data changes.
SwiftData makes saving app data easy and safe.
Mark your data classes with @Model and set up storage with .modelContainer(for:).
Use @Environment(\.modelContext) and @Query to work with your saved data in views.
Practice
@Model in SwiftData?Solution
Step 1: Understand the role of
The@Model@Modelattribute marks a class as a data model for SwiftData to manage persistence.Step 2: Recognize automatic data management
SwiftData automatically saves and tracks changes for classes marked with@Model.Final Answer:
It tells SwiftData to manage and save instances of that class automatically. -> Option CQuick Check:
@Modelmeans automatic data management [OK]
- Thinking @Model creates a UI component
- Assuming @Model disables saving
- Confusing @Model with view modifiers
Solution
Step 1: Recall the correct syntax for model container setup
SwiftData usesModelContainer(for: MyModel.self)to create a container for a single model type.Step 2: Identify the correct option
let container = ModelContainer(for: MyModel.self)uses the correct constructor syntax.Final Answer:
let container = ModelContainer(for: MyModel.self) -> Option AQuick Check:
Model container setup uses ModelContainer(for: Type.self) [OK]
- Using [MyModel].self array syntax incorrectly
- Using .modelContainer() which is a view modifier
- Forgetting .self after the type
struct ContentView: View {
@Environment(\.modelContext) private var context
@Query var items: [Item]
var body: some View {
List(items) { item in
Text(item.name)
}
}
}
What will happen if you add a new Item to context?Solution
Step 1: Understand @Query and @Environment(\.modelContext)
@Query fetches data from the model container and updates the view automatically when data changes.Step 2: Recognize automatic UI updates
Adding a newItemtocontexttriggers the @Query to refresh, updating the list.Final Answer:
The list will automatically update to show the new item. -> Option DQuick Check:
@Query updates UI on data change [OK]
- Thinking UI updates only on app restart
- Believing @Query is static data
- Assuming app crashes on data change
@Model
class Task {
var title: String
init(title: String) {
self.title = title
}
}
What is the likely cause of the crash?Solution
Step 1: Check SwiftData model requirements
SwiftData requires model classes to have a default initializer or all properties to have default values.Step 2: Identify missing default initializer
The class has a custom initializer but no default one, causing runtime issues.Final Answer:
The class is missing a default initializer for SwiftData. -> Option AQuick Check:
SwiftData models need default initializers [OK]
- Thinking @Model requires final keyword
- Making properties optional unnecessarily
- Believing only structs can be @Model
Book with a title and optional author. You also want to fetch all books with a non-empty author in a SwiftUI view. Which code snippet correctly defines the model and query?Solution
Step 1: Define model with optional author and default values
@Model class Book { var title: String = "" var author: String? = nil }@Query(filter: #Predicate { $0.author != nil && !$0.author!.isEmpty }) var books: [Book]correctly definesauthoras optional with a default nil andtitlewith a default empty string.Step 2: Use a filter predicate to fetch books with non-empty author
The filter checksauthor != niland thatauthoris not empty, matching the requirement.Final Answer:
Correctly defines the model and query for non-empty authors. -> Option BQuick Check:
Optional author + filter for non-empty =@Model class Book { var title: String = "" var author: String? = nil }@Query(filter: #Predicate { $0.author != nil && !$0.author!.isEmpty }) var books: [Book][OK]
- Forgetting to make author optional
- Using empty string author without optional
- Incorrect filter logic for non-empty strings
Ready to prove it?
Pass the test and this pattern moves unknown
