Post

Replies

Boosts

Views

Activity

Reply to No "upsert" when working with .unique attributes
I also did not know what to do, here is my test model: @Model final class Item { @Attribute(.unique) var name: String init(name: String) { self.name = name } } Here is my test code: func doTest() { let item1 = Item(name: "John") let item2 = Item(name: "John") let item3 = Item(name: "Peter") modelContext.insert(item1) try? modelContext.save() print("hello \(item1.name)") // <-- exception } And we have no methods to check what happened to non-unique items. And then I had an idea which worked for me, it is very simple, so instead of String type you should use String? (I know, this is inconvenient), but then if the item was non-unique the .name property will be set to nil! So change you model to this @Model final class Item { @Attribute(.unique) var name: String? // <--- here (optional String) init(name: String) { self.name = name } } And now func doTest() { let item1 = Item(name: "John") let item2 = Item(name: "John") let item3 = Item(name: "Peter") modelContext.insert(item1) try? modelContext.save() // yeah, item1 was non-unique so it is now having a nil name if item1.name != nil { print("hello \(item1.name!)") } } Hope this, helps!
Aug ’23