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

前端 未结 4 1604
你的背包
你的背包 2020-12-09 07:13

(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 o

相关标签:
4条回答
  • 2020-12-09 07:53

    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.

    0 讨论(0)
  • 2020-12-09 07:56

    If you end up here with this:

    @NSManaged var boolAttribute: Bool
    

    and it is not being seen in Objective-C, and you have already disabled "Optional" and enabled "Use Scalar Type" on those attributes, then do yourself a favour.

    Double check you have imported your Swift bridging header into that Objective-C file.

    I did not and, well, I was most of the way to changing my Bools to NSNumbers before smacking my head and realising how foolish I had been.

    0 讨论(0)
  • 2020-12-09 07:57

    I could use Objective-C types to manage these cases. 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
    
    0 讨论(0)
  • 2020-12-09 08:08

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

    0 讨论(0)
提交回复
热议问题