Portrait

I2H3

Notes from work as an app developer for iPhones, iPads and Macs.

RSS Icon GitHub Mastodon

@Attribute(.unique) Causes Model Replacement

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.

a memoji

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.