SwiftData Upsert

How do I get Upsert to work in SwiftData?

I have a model:

@Model
class Address: Identifiable {
    @Attribute(.unique)
    var id: Int = 0
    
    var number: String = ""
    var street: String?
    var city: String?
}

When I insert a duplicate record with the same data attributes (specifically overlapping id) and execute modelContext.save() I receive a EXC_BREAKPOINT.

let addressA = Address(id: 1, number: "2300", street: "E Main St", city: "Small Town" );
modelContext.insert(addressA)
try? modelContext.save()


let addressAv2 = Address(id: 1, number: "2300", street: "E Main St", city: "Small Town" );
modelContext.insert(addressAv2)
try? modelContext.save() // This fails

Is there a better way to handle updates?

did you find any updates? In my case it doesn't crash but it inserts the duplicate anyway, it doesn't properly upsert the existing one.

SwiftData Upsert
 
 
Q