有没有一种方法可以为Optional值创建扩展,这样我们就无需单独创建自定义绑定。
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)
}
}
}
我正在考虑做这样的事情
extension Optional where Wrapped == String {
func optionalBinding() -> Binding<String> {
return Binding(get: {
self ?? ""
}, set: { newValue in
self = newValue
})
}
}
对此有何建议?
答案 0 :(得分:1)
您可以尝试扩展Binding
而不是Optional
:
extension Binding where Value == String? {
var optionalBinding: Binding<String> {
.init(
get: {
self.wrappedValue ?? ""
}, set: {
self.wrappedValue = $0
}
)
}
}
并像这样使用它:
class ViewModel: ObservableObject {
@Published var text: String?
}
struct ContentView: View {
@ObservedObject var model = ViewModel()
var body: some View {
VStack {
TextField("Text", text: $model.text.optionalBinding)
Text(String(describing: model.text))
}
}
}