0

I have a core data model that contains mainly optional attributes. I assumed then that I would not need to unwrap the values that I am assigning to these optional attributes. e.g. I thought I would be able to do:

myEntity.gravity = currentOrder.gravity

(myEntity.gravity being optional)

However, Swift still requires me to unwrap currentOrder.gravity. I would have thought given that the variable I am assigning to is optional that I would not need to unwrap this.

Update:

Here is the definition of one of the core data entities I am describing:

    <attribute name="percentComplete" optional="YES" attributeType="Float" defaultValueString="0.0" usesScalarValueType="YES"/>

The entity itself:

    <entity name="AircraftMeasurementsCD" representedClassName="AircraftMeasurementsCD" syncable="YES" codeGenerationType="class">
DevB1
  • 1,235
  • 3
  • 17
  • 43
  • What you're describing should be true. I suspect that `myEntity` or `currentOrder` aren't defined quite the way you think they are. You should show the exact definitions of these from your code. – Rob Napier Jun 04 '20 at 15:16
  • Thanks @RobNapier I just added the definitions of one of the optional attributes along with the entity it belongs to... – DevB1 Jun 04 '20 at 15:22

1 Answers1

2

It seems you're equivocating on the word "optional". The word "optional" in the attribute description optional="YES" is not the same as, and has nothing to do with, the Swift Optional enum type.

The former is merely the ordinary English word "optional", meaning "not required" — for a particular entity, there might or might not be a value for this attribute, which is a Float, but even if there isn't, it's a valid entity. Nothing in the story says that this attribute's type is Optional<Float>. Its type is Float. And you can't assign a Swift Optional where its wrapped type is expected; you have to unwrap it.

Indeed, this point is made very explicitly by the documentation:

Optional attributes aren’t required to have a value when saved to the persistent store. Attributes are optional by default. Core Data optionals aren’t the same as Swift optionals. [My italics.]

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • thanks for the response - so in this case there is no way to avoid unwrapping these? This issue I'm facing is that I have a fairly lengthy list of attributes (around 70 in total) and it appears i need to unwrap each one individually – DevB1 Jun 04 '20 at 15:31
  • I don't know anything about why `currentOrder.gravity` is an Optional, because you have not told me. Maybe it needs to be, maybe it doesn't; I have no way of knowing, that isn't part of your question, either. Maybe you'd like to ask a different question about architecting your types? Meanwhile, what you _did_ ask is why an `Optional` cannot be assigned directly to `myEntity.gravity` and I think I answered that. – matt Jun 04 '20 at 15:33
  • fair enough, understood – DevB1 Jun 04 '20 at 15:37