Post

Replies

Boosts

Views

Activity

Safely converting optional state to non optional binding
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.
1
1
3.7k
Nov ’22
Safely converting optional state to non optional binding
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.
Replies
1
Boosts
1
Views
3.7k
Activity
Nov ’22