@Attribute(.unique) Causes Model Replacement
February 2, 2024
While making my first experiences with SwiftData, I also used @Attribute(.unique)
on a model property.
I expected model insertion to throw an error or crash in case this constraint is violated.
The actual behaviour was rather surprising.
Once you create another model with the same value for that unique property, it will simply replace the existing item.
You can reproduce it yourself with the Xcode template project for a macOS app which uses SwiftUI and SwiftData. Just add a unique name property to it so it looks like this:
@Model
final class Item {
@Attribute(.unique)
var name: String
var timestamp: Date
init(name: String, timestamp: Date) {
self.name = name
self.timestamp = timestamp
}
}
And upon creation always hand over the same value:
let newItem = Item(name: "Always the same", timestamp: Date())
modelContext.insert(newItem)
If you take a look into the database (I use Core Data Lab for that), then you will see that after multiple insertions there still is only one item.