I’ve created a simple example that’s crashing my previews.
The code below crashes when the text is tapped, with the error saying that it found nil
when trying to force unwrap itemToShow
.
This doesn’t make sense to me since the code assigns itemToShow
to a non-nil value before showing the sheet with showSheet = true
.
struct TestView: View {
@State var showSheet = false
@State var itemToShow: String? = nil
var body: some View {
Text("Show sheet")
.onTapGesture {
itemToShow = "Apple"
showSheet = true
}
.sheet(isPresented: $showSheet) {
Text(itemToShow!)
}
}
}
I’m guessing this has something to do with how SwiftUI updates views, but why is this error happening and what’s a possible fix?
1