(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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…