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? xcode xcode

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.


This happens because Objective-C scalar types do not have a notion of nil value. Source: handling-core-data-optional-scalar-attributes


I would rather use Objective-C types to manage these cases than Swift types.In these cases, for scalars types, you can use NSNumber.

 @NSManaged public var myDouble: NSNumber?

In the model myDouble is an optional double with nil value by default.

To get the real value you only need to use:

myEntity.myDouble?.doubleValue