I have a simple model with a unique field.
@Model
class M {
@Attribute(.unique)
var value: String
var date: Date
var answer: Int
init(value: String, date: Date = .now, answer: Int = 0) {
self.value = value
self.date = date
self.answer = answer
}
}
I am creating new objects with
let x = M(value: "x")
modelContext.insert(x)
The value
field has a unique constraint, and I am observing these differences in iOS 18 beta (Xcode 16.0 beta) from iOS 17.5 (Xcode 15.4):
- Multiple objects with the same
value
field appear in the list. - If explicit
modelContext.save()
is called, list is not updated with latest values.
Is this something I need to adjust to, or beta issues?
Full source code: https://github.com/paiv/swiftdata-insert-unique-1
Thanks for confirming in your comment that explicitly saving the context fixes the issue. Meanwhile, I'd suggest that you file a feedback report with your sample project and the discussion here for the SwiftData team to review their change in this regard.