Component - SwiftData setup (modern persistence)
This UI component demonstrates setting up SwiftData for modern data persistence in an iOS app. It shows how to initialize the data model, inject the model context, and display saved data in a list.
This UI component demonstrates setting up SwiftData for modern data persistence in an iOS app. It shows how to initialize the data model, inject the model context, and display saved data in a list.
App > WindowGroup > ContentView > NavigationView > List > Text
@Model in SwiftData?@Model@Model attribute marks a class as a data model for SwiftData to manage persistence.@Model.@Model means automatic data management [OK]ModelContainer(for: MyModel.self) to create a container for a single model type.let container = ModelContainer(for: MyModel.self) uses the correct constructor syntax.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?Item to context triggers the @Query to refresh, updating the list.@Model
class Task {
var title: String
init(title: String) {
self.title = title
}
}
What is the likely cause of the crash?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?@Model
class Book {
var title: String = ""
var author: String? = nil
}
@Query(filter: #Predicate { $0.author != nil && !$0.author!.isEmpty }) var books: [Book] correctly defines author as optional with a default nil and title with a default empty string.author != nil and that author is not empty, matching the requirement.@Model
class Book {
var title: String = ""
var author: String? = nil
}
@Query(filter: #Predicate { $0.author != nil && !$0.author!.isEmpty }) var books: [Book] [OK]Pass the test and this pattern moves unknown