Say you have a SwiftData object that doesn't allow optionals:
@Model
class MySet: Identifiable {
var id: UUID
var weight: Int
var reps: Int
var isCompleted: Bool
var exercise: Exercise
Then you get from your MySet data a list of these MySets and append them into a State:
@State var sets: [MySet]
if let newSets = exercise.sets { //unwrapping the passed exercises sets
if (!newSets.isEmpty) { //we passed actual sets in so set them to our set
sets = newSets
}
And you use that State array in a ForEach and bind the Textfield directly to the data like so:
ForEach($sets){ $set in
TextField("\(set.weight)", value: $set.weight, formatter: NumberFormatter())
.keyboardType(.decimalPad)
TextField("\(set.reps)", value: $set.reps,formatter: NumberFormatter())
.keyboardType(.decimalPad)
}
This will bind whatever is written into the TextField directly to the SwiftData object which is a problem because say you have 50 written and you want to change it to 60 you need to be able to clear the 50 to write the 60 and since the SwiftData object doesn't allow nil it will allow you to remove the 0 but not the 5. Is there anyway to remedy this without having the swiftData object allow optionals for example catching the clearing of the TextField and making it 0 instead of nil when its cleared?