I’ve got this simple view and it doesn’t work as expected. When clicking the button a new Event
is 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?