Exception when setting an optional binding to nil in SwiftUI after checking
Here is a possible approach to fix this. Tested with Xcode 12 / iOS 14.
The-Variant! - Don't use optional state/binding & force-unwrap ever :)
Variant1: Use binding wrapper (no other changes)
CRTestView(optional: Binding(
get: { self.optional ?? -1 }, set: {self.optional = $0}
))
Variant2: Transfer binding as-is
struct ContentView: View {
@State var optional: Int?
var body: some View {
VStack {
if optional == nil {
Text("Nil")
} else {
CRTestView(optional: $optional)
}
Button(action: {
if optional == nil {
optional = 0
} else {
optional = nil
}
}) {
Text("Toggle")
}
}
}
}
struct CRTestView: View {
@Binding var optional: Int?
var body: some View {
VStack {
Text(optional?.description ?? "-1")
Button(action: {
optional? += 1
}) {
Text("Increment")
}
}
}
}