How to Represent Core Data Optional Scalars (Bool/Int/Double/Float) in Swift

How to represent Core Data optional Scalars (Bool/Int/Double/Float) in Swift?

I see the same thing, and I consider it to be a bug. It's not documented anywhere that I can find. Apparently Core Data is applying Objective-C style assumptions here, where a boolean defaults to NO, and an integer defaults to 0. The Core Data/Swift interface has some rough edges, and this is one I hadn't considered before.

It's a good find but I think you're stuck with it until Apple addresses it. You already know the best workarounds, which I agree aren't great. I recommend filing a bug.

Storing coordinate from Core Location in Core Data. Float or Double?

A 32-bit float holds 7 digits of precision, a 64-bit double holds 15 digits of precision.

With 7 digits of precision the maximum longitude of 179.9999 is only accurate down to 0.0001 degrees. A degree is about 60 nautical miles so 0.0001 degrees is about 10 meters (33 feet). If you want to store more precise lat/lon values, then you need to use a double (or a fixed point integer).

Core data | automatically generated String and Date attributes are optional even when not marked in swift

Two options

  • Edit the MyManagedObject to make them non-optional. This means you need to maintain this class yourself and do any changes both in the core data model and the class
  • Create a protocol (or sub class) with same attributes (you need to give them new names) but non-optional and implement this protocol in a separate extension to get and set original attributes and then use this protocol rather than MyManagedObject in your code.

If your data model is stable and won't be changed that much the first option is probably best.

Xcode NSManagedObject subclass contains optionals when they are marked as non-optional

"Optional" means something different to Core Data than it does to Swift.

  • If a Core Data attribute is not optional, it must have a non-nil value when you save changes. At other times Core Data doesn't care if the attribute is nil.
  • If a Swift property is not optional, it must have a non-nil value at all times after initialization is complete.

Making a Core Data attribute non-optional does not imply that it's non-optional in the Swift sense of the term. That's why generated code makes these properties optional-- as far as Core Data is concerned, it's legal to have nil values except when saving changes.



Related Topics



Leave a reply



Submit