Attributes as Swift optional?

Hi,


I have an entity with a Double attribute. It is marked as "optional" -- ie, the checkbox is checked in the Core Data inspector in Xcode. It generates this Swift code in the entity class:


@NSManaged public var height: Double


I was expecting it to be `Double?`. Wouldn't that make more sense? I'd like to differentiate between a purposely set value of 0.0, and a nil (ie, never set). Is this supported? If so, is there a way to make it generate the code that way (with `Double?`), or do I need to turn off code generation and write my own subclass of NSManagedObject for this entity?


(Xcode 8, beta 6)


thanks,

Rob

Accepted Reply

You cannot use `Double?` for `@NSManaged` attributes, even if you write your own NSManagedObject class yourself:

property cannot be marked @NSManaged because its type cannot be represented in Objective-C

...is what you get for `@NSManaged public var height: Double?`.


`NSManagedObject` utilizes runtime features of Objective-C, so you cannot have an attribute which cannot be represented in Objective-C.


If you want to make the attribute Optional, you may need to change the type to `Decimal`, or choose `NSNumber` to represent the value.

Replies

You cannot use `Double?` for `@NSManaged` attributes, even if you write your own NSManagedObject class yourself:

property cannot be marked @NSManaged because its type cannot be represented in Objective-C

...is what you get for `@NSManaged public var height: Double?`.


`NSManagedObject` utilizes runtime features of Objective-C, so you cannot have an attribute which cannot be represented in Objective-C.


If you want to make the attribute Optional, you may need to change the type to `Decimal`, or choose `NSNumber` to represent the value.