I have a view with a State
variable which is an Optional
. I render the view by first checking if the optional variable is nil, and, if it is not, force unwrapping it and passing it into a subview using a Binding
.
However, if I toggle the optional variable between a value and nil
, the app crashes and I get a EXC_BAD_INSTRUCTION
in the function BindingOperations.ForceUnwrapping.get(base:)
. How can I get the expected functionality of the view simply displaying the 'Nil' Text
view?
struct ContentView: View {
@State var optional: Int?
var body: some View {
VStack {
if optional == nil {
Text("Nil")
} else {
TestView(optional: Binding($optional)!)
}
Button(action: {
if optional == nil {
optional = 0
} else {
optional = nil
}
}) {
Text("Toggle")
}
}
}
}
struct TestView: View {
@Binding var optional: Int
var body: some View {
VStack {
Text(optional.description)
Button(action: {
optional += 1
}) {
Text("Increment")
}
}
}
}