Understanding SwiftUI and control flow

I’ve got this simple view and it doesn’t work as expected. When clicking the button a new Eventis created and the flag used as binding for a sheet is set to true. This should show the sheet and give the sheet access to the Event. Instead I get the error message Fatal error: Unexpectedly found nil while unwrapping an Optional value.

I can’t see the problem. As far as I see this the tmpEvent variable should have a valid value once the sheet is presented.

import SwiftUI

struct TestView: View {
  @Environment(\.managedObjectContext) private var viewContext
  @State private var showingSheet = false
  @State private var tmpEvent: Event?
 
  var body: some View {
    VStack {
      Button(action: showSheet) {
        Label("Add event", systemImage: "plus.circle")
      }
    }
    .sheet(isPresented: $showingSheet) {
      Text("event title: \(tmpEvent!.descriptionString)"). // Fatal error occurs here
    }
  } 

  private func showSheet() {
    tmpEvent = Event(context: viewContext)
    showingSheet = true
  }
}

Any ideas why this isn’t working?

Hi, I also had some problems with sheets and a Binding Bool in the past. I would try two things.

Are you sure that the tmpEvent you set using showSheet() isn't returning an optional value that might be nil? you can try adding:

guard let tmpEvent = Event(context: viewContext) else{
print("found nil")
return
}

and if you see something in the log you know that it contains nil. This also prevents the sheet from being shown while the Event is nil.

In general I would avoid having optionals in your views because you always have to deal with optional values, or risking that your app is getting terminated because of force unwrapping.

If that doesn't work, try using an default value and see if it later on changes to the correct value. If this is the case, your sheet is presented before the event got an initial value...

Take care, David

Understanding SwiftUI and control flow
 
 
Q