Search code examples
swiftuinsmanagedobject

Display NSManagedObject field in SwiftUI form


I want to display a form using the data from an NSManagedObject.

Here is my form:

struct RecordForm: View
{
    @State var record: Record // NSManagedObject

    var body: some View
    {
        Form
        {
            TextField("name", text: $record.recordName) // Cannot convert value of type 'Binding<String?>' to expected argument type '_?'
        }
    }
}

So it's obviously not liking the optional value, but I cannot find the syntax to address this. Adding an exclamation mark doesn't fix it.


Solution

  • Binding has explicit constructor for optionals. Try the following

    Form
    {
        TextField("name", text: Binding<String>($record.recordName))
    }