Is there a way to create an extension for Optional value so that we don't need to create custom binding individually.
class ViewModel: ObservableObject {
@Published var text: String?
}
struct ContentView: View {
@ObservedObject var model: ViewModel
var body: some View {
let binding = Binding(
get: { self.model.text ?? "" },
set: { self.model.text = $0 }
)
return VStack {
TextField("Text", text: binding)
}
}
}
I'm thinking about doing something like this
extension Optional where Wrapped == String {
func optionalBinding() -> Binding<String> {
return Binding(get: {
self ?? ""
}, set: { newValue in
self = newValue
})
}
}
Any suggestions on this?