Search code examples
iosswiftcore-dataswiftui

SwiftUI core data optional and non-optional properties


I am having trouble with a core data entity and SwiftUI. In my view, some properties are non-optional when they should be and I do not understand why.

Here is my Entry core data entity:

Entry core data entity

Here is how I am attempting to use this in a view:

if entry.text != nil {
    Text(entry.text!)
}

if entry.number != nil {
    Text("\(entry.number, specifier: "%.0f")")
}

if entry.boolean != nil {
    Text(entry.boolean ? "True" : "False")
}

My issue is that for entry.number and entry.boolean, swift complains of Comparing non-optional value of type 'Double' to 'nil' always returns true.

This does not happen for entry.text. I have checked the values by running print(entry) and number and boolean are nil in the persistent store.

I understand that core data optionals and swift optionals are different. However, shouldn't all Entry properties be optional in this case? Why is SwiftUI complaining that they are not?


Solution

  • When you create your entity the default setting for Boolean and Double is to use scalar (primitive) types and they are non-optional because Objective-C (which is what Core Data is based on) can't handle optional scalar types.

    This is how they are defined in code

    @NSManaged public var boolean: Bool
    @NSManaged public var number: Double
    

    If you uncheck to use scalar type (Inspector Cmd-alt-0) then the underlying type would be NSNumber instead and they would be optional

    @NSManaged public var number: NSNumber?
    @NSManaged public var boolean: NSNumber?