SwiftData context disregards unique attribute

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

Answered by DTS Engineer in 790285022

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.

I tried your project and it doesn't seem that your project reproduces the issue. Here is what I did:

  1. Download and open your project with Xcode. I am on Xcode 15.4 + macOS Sonoma 14.5, the latest public releases.

  2. Un-comment line #50 in your ContentView.swift so the new item is saved immediately. This is needed because the validation of uniqueness happens when the context is saved.

  3. Run your app in my iOS simulator, and click Add multiple times. Observe that there is only one item, and that the time stamp is updated.

  4. Stop running your app, and then run it again. Observe the data is still there.

What version of Xcode and the simulator / device you are using? If you see the isse on beta systems, please file a feedback report with the build of the system + Xcode, and post your report ID here. I will take another look once catching a chance.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

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.

SwiftData context disregards unique attribute
 
 
Q