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.

Answered by BabyJ in 735312022

Could you not just do this:

// unwrap variable normally
if let nonOptional = optional_ {
    // create new binding using unwrapped value
    let binding = Binding { nonOptional } set: { optional_ = $0 }
    ChildView(nonOptional: binding)
    
    ...
}
Accepted Answer

Could you not just do this:

// unwrap variable normally
if let nonOptional = optional_ {
    // create new binding using unwrapped value
    let binding = Binding { nonOptional } set: { optional_ = $0 }
    ChildView(nonOptional: binding)
    
    ...
}
Safely converting optional state to non optional binding
 
 
Q