Skip to content

Instantly share code, notes, and snippets.

@dbonates
Last active January 18, 2023 13:57
Show Gist options
  • Save dbonates/7fee3fc7f87daf811145168fe2f7d219 to your computer and use it in GitHub Desktop.
Save dbonates/7fee3fc7f87daf811145168fe2f7d219 to your computer and use it in GitHub Desktop.

SwiftUI - Binding vs Coredata optional property vs TextEditor

If one tries to use a string property from a Coredata model on a TextField, like this:

TextEditor(text: $item.info)

will get this error

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

So an elegant/bridge solution could be create this, so Optional String will have a binding property that you can use:

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 }
    }
}

TextEditor(text: $item.info.bound)

or just create a Binding var and use it on TextEditor for manipulate the property like this:

var infoEditable: Binding<String> {
    Binding<String>(
        get: { return item.info ?? "" },
        set: { newInfo in item.info = newInfo }
    )
}

TextEditor(text: infoEditable)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment