How to assign an optional Binding parameter in SwiftUI?

@Binding var searchTxt: String?

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

Update: I prefer this one. 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 }
    )
}

Leave a Comment