Which Swift types can be represented in Objective-C?

Moon Cat picture Moon Cat · Jun 30, 2014 · Viewed 17.1k times · Source

I'm creating an NSManagedObject subclass in Swift and I get an error when I make an Optional property that's of type Int, Float or Double (and maybe others that I didn't try out).

@NSManaged var number: Float? //error:Property cannot be marked @NSManaged because its type cannot be represented in Objective-C
@NSManaged var anotherNumber: Float //no error
@NSManaged var array: NSArray? //no error
@NSManaged var anotherArray: Array<String>? //no error

Which optional types can be represented in Objective-C? Why does the error not appear when I'm using a Swift Array or String (and when I'm not using an Optional Int or Double)?

Answer

Martin R picture Martin R · Jun 30, 2014

You cannot assign arbitrary types to Core Data properties because the accessor methods are created dynamically at runtime. If you create an Objective-C managed object subclass in Xcode then you will see the proper data types used by Core Data, e.g.

  • NSNumber for Boolean, Integer, Float and Double attributes,
  • NSString for String attributes,
  • NSSet for (unordered) to-many relationships.

You have to choose the same data type in Swift.

Theoretically, scalar accessors for primitive data types should work as well, but there seems to be a problem in the current Swift version, compare How to use Core Data Integer 64 with Swift Int64? or EXC_BAD_ACCESS error when trying to change Bool property.