5

Here is my SwiftUI view:

struct EditEntity: View {
    @State var entity: Entity
    var body: some View {
        Form {
            TextField("Entity Name", text: $entity.name)
        }
    }
}

Entity is an object Core Data is creating for me using code generation.

And here is how that entity is set up in the Core Data model file:

Core Data model setup

And the issue I am having is that $entity.name is a Binding<String?> object, when SwiftUI wants a Binding<String> object. So I am getting this compile error:

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

So does anyone know what the best practise is for this? Should I create a seperate non-optional variable within the view class for the attribute? As can be seen in my screenshot, I set the attribute to not be optional in the hope it would be a non-optional string, but clearly that didn't work.

I found essentially this question asked here. And the answer there is to create an extension. Is this really what needs to be done when trying to use SwiftUI with Core Data together to do such a basic thing?

Jake Carr
  • 71
  • 7

2 Answers2

3

The following should help:

TextField("Entity Name", text: Binding($entity.name)!)
Asperi
  • 228,894
  • 20
  • 464
  • 690
0

I learned this technique from reading Jim Dovey's blog on SwiftUI Bindings with Core Data. It includes a nice pattern that can be replicated for a number of different data types.

First create an extension on Binding

public extension Binding where Value: Equatable {
    init(_ source: Binding<Value?>, replacingNilWith nilProxy: Value) {
        self.init(
            get: { source.wrappedValue ?? nilProxy },
            set: { newValue in
                if newValue == nilProxy { source.wrappedValue = nil }
                else { source.wrappedValue = newValue }
            }
        )
    }
}

Then use in your code like this...

TextField("Entity Name", text: Binding($entity.name, replacingNilWith: ""))

This is based upon the fact that in your Core Data model editor, you keep your Entity attribute name as Optional (checked).

andrewbuilder
  • 3,629
  • 2
  • 24
  • 46