I have the following model:
struct Food: Codable, Identifiable {
var id = UUID()
var name: String = ""
var energy: Float?
var water: Float?
var macroProfile: MacronutrientProfile?
}
struct MacronutrientProfile: Codable {
var carb: Float?
var protein: Float?
var fat: Float?
}
I am trying to bind values of an instance of this model to TextField
as such:
struct FoodEditView: View {
@State var food: Food
var body: some View {
Form {
Section(header: Text("Basics").fontWeight(.bold)) {
HStack {
Text("Name")
Spacer()
TextField("Name", text: $food.name)
.multilineTextAlignment(.trailing)
}
HStack {
Text("Energy")
Spacer()
TextField("Calories", value: $food.energy, formatter: calorie)
.multilineTextAlignment(.trailing)
.keyboardType(.numberPad)
}
HStack {
Text("Water")
Spacer()
TextField("Grams", value: $food.water, formatter: gram)
.multilineTextAlignment(.trailing)
.keyboardType(.numberPad)
}
}
.textCase(.none)
Section(header: Text("Macronutrients").fontWeight(.bold)) {
HStack {
Text("Carbohydrates")
Spacer()
TextField("Grams", value: $food.macroProfile?.carb, formatter: gram)
.multilineTextAlignment(.trailing)
.keyboardType(.numberPad)
}
HStack {
Text("Protein")
Spacer()
TextField("Grams", value: $food.macroProfile?.protein, formatter: gram)
.multilineTextAlignment(.trailing)
.keyboardType(.numberPad)
}
HStack {
Text("Fat")
Spacer()
TextField("Grams", value: $food.macroProfile?.fat, formatter: gram)
.multilineTextAlignment(.trailing)
.keyboardType(.numberPad)
}
}
.textCase(.none)
I am this rather strange, long list of errors when chaining macroProfile
:
My question is, how is it that I am getting these errors when optional chaining macroProfile
and not when using energy
or water
, both of which are also optional values? And what is the best approach to fix this?