swiftui

SwiftUI Optional TextField


Can SwiftUI Text Fields work with optional Bindings? Currently this code:

struct SOTestView : View {
    @State var test: String? = "Test"

    var body: some View {
        TextField($test)
    }
}

produces the following error:

Cannot convert value of type 'Binding< String?>' to expected argument type 'Binding< String>'

Is there any way around this? Using Optionals in data models is a very common pattern - in fact it's the default in Core Data so it seems strange that SwiftUI wouldn't support them


Solution

  • Ultimately the API doesn't allow this - but there is a very simple and versatile workaround:

    extension Optional where Wrapped == String {
        var _bound: String? {
            get {
                return self
            }
            set {
                self = newValue
            }
        }
        public var bound: String {
            get {
                return _bound ?? ""
            }
            set {
                _bound = newValue.isEmpty ? nil : newValue
            }
        }
    }
    

    This allows you to keep the optional while making it compatible with Bindings:

    TextField($test.bound)