My Swift program is crashing with :Unexpectedly found nil while unwrapping an Optional value. What does this error mean, and how do I fix it?

121 views Asked by At

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 .

enter image description here

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 

        })
    }
}

2

There are 2 answers

0
malhal On BEST ANSWER

It's because you forgot to call the showFood getter somewhere in body which is how SwiftUI decides if body 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:

sheet(isPresented: $shouldShowSheet) { [showFood] {

But it would be best if you used a different sheet modifier, e.g.

.sheet(item: $showFood) {

Now a new sheet will be recreated when showFood changes and it will have the latest value and not crash.

0
son On

I encountered this issue before, and it seems like SwiftUI couldn't determine a @State object that doesn't conform to Equatable in such this circumstance. You can either change to .sheet(item:) or make Food fully conform to Equatable to fix this.

struct Food: Identifiable, Equatable {
  static func == (lhs: Food, rhs: Food) -> Bool {
    ...
  }
}