(first noticed on: Xcode 8.2.1, iOS 10, Swift 3) (still present as of: Xcode 9 beta 3, iOS11, Swift 4)
We all know that the Core Data
concept of optionals
precedes and is not strictly tied to the Swift
concept of optionals
.
And we have accepted that even if a Core Data
attribute is marked as Non-optional
, the auto-generated NSManagedObject
subclass has an optional
type:
(some people manually remove the ?
with no adverse effects, some don't, but that's beside the point)
(From here on the example and screenshots are for Bool
properties, but same goes for Int16/32/64
, Double
, Float
)
Now I noticed the reverse - when a Core Data
attribute of type Bool
is marked as Optional
(and Use Scalar Type
is chosen, which Xcode does by default), the auto-generated class has a variable of a non-optional
type.
Does this make sense? Is it a bug? Is the behaviour documented anywhere?
And most importantly - how do I actually represent an optional Bool
?
I can think of some work-arounds, but they don't seem ideal (e.g. not using scalars, but going back to NSNumber
representation of the Bool
. Or (even worse) having a separate Bool
called something like isVerified_isSet
)
Note: I did a couple more tests and if the Default Value
is set to None
or to NO
, then the variable gets saved as false
(even if I never actually assign it in my code). If the Default Value
is set to YES
, then the variable gets saved as true
. Still, this means that (apparently) there is no way to logically represent this variable as not having been set yet.
Scalar TypesCore Data has support for many common data types like integers, floats, booleans, and so on. However, by default, the data model editor generates these attributes as NSNumber properties in the managed object subclasses.
An optional acts as a container for a value of a particular type. The container holds a value or it doesn't. Type safety is a cornerstone of the Swift language. As a result, variables and constants need to be initialized before they can be accessed.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With