Have a data model that sets certain fields as unique. If the user attempts to save a duplicate value, the save fails quietly with no indication to the user that the save failed. The program is on Mac OS 26.0.1
@Environment(\.modelContext) var modelContext
@Query private var typeOfContracts: [TypeOfContract]
@State private var typeName: String = ""
@State private var typeCode: String = ""
@State private var typeDescription: String = ""
@State private var contracts: [Contract] = []
@State private var errorMessage: String? = "Data Entered"
@State private var showAlert: Bool = false
var body: some View {
Form {
Text("Enter New Contract Type")
.font(.largeTitle)
.foregroundStyle(Color(.green))
.multilineTextAlignment(.center)
TextField("Contract Type Name", text: $typeName)
.frame(width: 800, height: 40)
TextField("Contract Type Code", text: $typeCode)
.frame(width: 800, height: 40)
Text("Contract Type Description")
TextEditor(text: $typeDescription)
.frame(width: 800, height: 200)
.scrollContentBackground(.hidden)
.background(Color.teal)
.font(.system(size: 24))
Button(action: {
self.saveContractType()
})
{
Text("Save new contract type")
}
}
}
func saveContractType() {
let typeOfContract = TypeOfContract(contracts: [])
typeOfContract.typeName = typeName
typeOfContract.typeCode = typeCode
typeOfContract.typeDescription = typeDescription
modelContext.insert(typeOfContract)
do {
try modelContext.save()
}catch {
errorMessage = "Error saving data: \(error.localizedDescription)"
}
}
}
I have tried to set alerts but Xcode tells me that the alerts are not in scope
Thanks for provide the code. I don't see it has anything that should trigger a failure though. If you can elaborate a bit more about what failure you expect to see, I may take another look.
To comment your following description:
When I was saving a duplicate field value, it was not failing, it was replacing the current with a new record, thus it remained unique because the old record was replaced.
This behavior is as-designed, and is known as upsert
. For a model that has a unique attribute, when you add a new object and there already exists another object that has the same value for the unique attribute, SwiftData updates the existing object with the new one. No error will be triggered in this case.
For models that don't have any unique attribute, objects are identified by persistentModelID, which is managed by SwiftData. You can add multiple objects that have same values for all the attributes you define, without triggering any conflict.
Best,
——
Ziqiao Chen
Worldwide Developer Relations.