Line 30 set the value to showFood, and the line 32 print it ,is not null. but the line 49 show variable showFood is nil and get error. I do not know why.
i have try my best ,but i donot why showFood on line 49 is nil .
code below
import SwiftUI
struct TestView: View {
@Environment(\.dynamicTypeSize) private var textSize
@Environment(\.editMode) var editModel
@State var food = Food.examples
@State var shouldShowSheet: Bool = false
@State var selectedFoodID = Set<Food.ID>()
@State var selectedFood: Binding<Food>?
var isEditing: Bool {
editModel?.wrappedValue == .active
}
@State var shouldShowForm: Bool = false
@State var showFood: Food?
var body: some View {
VStack(alignment: .leading) {
List($food, editActions: .all, selection: $selectedFoodID) { $food in
HStack {
Text(food.name)
.onTapGesture {
showFood = food
print(showFood) // showFood here is not null
}
}
}
}.sheet(isPresented: $shouldShowSheet, content: {
let foo = showFood! // showFood is null. and get error here. i donot why
})
}
}
It's because you forgot to call the
showFood
getter somewhere inbody
which is how SwiftUI decides ifbody
needs to be called when a state is set. This usually means you've declared the wrong kind of@State
. As a quick fix you can workaround the problem by faking a read like:But it would be best if you used a different sheet modifier, e.g.
Now a new sheet will be recreated when showFood changes and it will have the latest value and not crash.