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