You create a new entity instance and call modelContext.insert(newEntity) followed by try? modelContext.save(). What is the expected behavior?
@Model class Task { var title: String init(title: String) { self.title = title } } let newTask = Task(title: "Buy milk") modelContext.insert(newTask) try? modelContext.save()
Think about what modelContext.save() does in SwiftData.
Calling modelContext.insert() adds the entity to the context. Then modelContext.save() writes changes to persistent storage, so the new entity is saved permanently.
You have a fetched Task entity and want to update its title. Which option is correct?
func updateTaskTitle(task: Task, newTitle: String) {
// update code here
try? modelContext.save()
}SwiftData entities use property wrappers for attributes.
You update the attribute directly by assigning a new value to the property. Then saving the context persists the change.
You call modelContext.delete(entity) but do not call modelContext.save(). What is the result?
Think about when changes are committed to disk in SwiftData.
Deleting an entity marks it for removal in the context, but changes are only saved to disk when save() is called. Without saving, the deletion is not permanent.
You display a list of Task entities fetched from SwiftData. After adding a new task, the list does not update automatically. What should you do?
SwiftUI and SwiftData integration uses property wrappers for reactive updates.
The @Query property wrapper automatically fetches and updates the list when the data changes, so the UI stays in sync.
Given this entity definition and save code, why does saving fail?
@Model
class User {
@Attribute(.unique) var email: String
init(email: String) {
self.email = email
}
}
let user1 = User(email: "a@example.com")
let user2 = User(email: "a@example.com")
modelContext.insert(user1)
modelContext.insert(user2)
try modelContext.save()Look at the attribute modifiers and what they enforce.
The .unique attribute means no two entities can have the same email. Inserting two with identical emails causes a validation error on save.