简体   繁体   中英

Optional @State variable not initializing

I want to be able to open a sheet view where the user taps on something on a list, and all the information from that tapped list cell shows up on the sheet view. However, I am having a hard time trying to initialize the optional @State variable to the list value. This is the error I get:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

The State variable seems to remain empty, hence why the code is replying with it getting a nil value. How can I get an actual value to be inside so it's not nil?

Any help would be appreciated.

My code is below:

struct ContentView: View {
    
    @Environment(\.managedObjectContext) var managedObjContext
    @FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)]) var counters: FetchedResults<Counter>
    
    @State private var creatingCounter = false
    @State private var editingCounter = false
    @State private var selectedCounter: FetchedResults<Counter>.Element? // The optional State var.
    
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(counters) { counter in
                        TimelineView(.periodic(from: .now, by: 1.0)) { timeline in
                            CounterCellView(title: counter.title ?? "", icon: counter.icon ?? "", color: counter.color ?? "", date: counter.date ?? Date())
                        }
                        .listRowSeparator(.hidden)
                        .onTapGesture {
                            selectedCounter = counter // I want the state var to be initialized to the tapped item on the list.
                            editingCounter.toggle()
                        }
                    }
                    .onDelete(perform: deleteCounter)
                    
                }
                .listStyle(.inset)
            }
            .navigationTitle("Counters")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        creatingCounter.toggle()
                    } label: {
                        Image(systemName: "plus")
                    }
                }
            }
        }
        .sheet(isPresented: $creatingCounter) {
            CreateCounterView(creatingCounter: $creatingCounter)
        }
        .sheet(isPresented: $editingCounter) {
            EditCounterView(editingCounter: $editingCounter, counter: selectedCounter!) // Where I am getting the error.
        }
    }
    
    func deleteCounter(at offsets: IndexSet) {
        
        withAnimation {
            offsets.map { counters[$0] }.forEach(managedObjContext.delete)
            DataController().save(context: managedObjContext)
        }
    }
}

try this approach:

remove all editingCounter and use something like this .sheet(item: $selectedCounter) , instead of your .sheet(isPresented: $editingCounter) :

.sheet(item: $selectedCounter) { kounter in    // <-- here
    if let theCounter = kounter {
        //-- here, adjust the EditCounterView (ie remove the editingCounter)
        EditCounterView(counter: theCounter)  
    }
}
    

If need be, your may have to declare @State private var selectedCounter: Counter?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM