Post not yet marked as solved
Post marked as unsolved with 1 replies, 2,210 views
Hi,
How would we safely convert an optional state to a non optional binding variable?
Using Binding<V?> to Binding<V>? with optional binding (if let) crashes if V is later set to nil.
Below is a minimal reproducible example.
import SwiftUI
struct ChildView: View {
@Binding var nonOptional: String
var body: some View {
Text("text that does not use the binding variable")
}
}
struct ContentView: View {
@State var optional_: String? = "test"
var body: some View {
if let nonOptional = Binding($optional_) {
ChildView(nonOptional: nonOptional)
Button(action: {
optional_ = nil // crashes after tapping
}) {
Text("set to nil")
}
} else {
Text("text is nil")
}
}
}
Error:
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1ba385a30)
in App.swift.
I am not interested in using "" or other default values, since this only works well with strings, and misses the point of my question.
Thanks.