How to assign an optional Binding parameter in SwiftUI? How to assign an optional Binding parameter in SwiftUI? swift swift

How to assign an optional Binding parameter in SwiftUI?


@Binding var searchTxt: String?init(searchTxt: Binding<String?>?) {    self._searchTxt = searchTxt ?? Binding.constant(nil)}

Or consider this: TextField("", text: $text ?? "default value")

https://stackoverflow.com/a/61002589/4728060

func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {    Binding(        get: { lhs.wrappedValue ?? rhs },        set: { lhs.wrappedValue = $0 }    )}


What you want is an Optional Binding of a String, not a Binding of an Optional String. I don't think you can achieve that by using the @Binding annotation.

However, you don't need to used the annotation. You can just declare the variable as a Binding:

Your

@Binding var searchTxt: String?

then turns to this

var searchTxt: Binding<String?>

But this way the syntax lets you place the ? wherever you want. So if you move it to the end, after the Binding's closing tag, you have what you want.

var searchTxt: Binding<String>?

If you want to access the String inside your Binding, you have to use the wrappedValue property.

Text(searchTxt!.wrappedValue)


I have a UIViewControllerRepresentable in order to use UIImagePickerController. If you've ever used this image picker, you know that you need to image returned to be an optional. So in my ContentView I declared:

@State var uiImage: UIImage?...if uiImage != nil {    Image(uiImage: $uiImage)} else {    Rectangle()}

And in my ImagePicker (that's my SwiftUI view) I have:

@Binding var uiImage: UIImage?

Works like a charm.

(The if statement is pretty much psuedo-code, as I'm actually using an MTKView and a CIImage, but your get the drift - you use the optional just as you would anywhere else.)