Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Swift types can be represented in Objective-C?

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)?

like image 873
Moon Cat Avatar asked Jun 30 '14 10:06

Moon Cat


People also ask

Does Objective-C work with Swift?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

How do you inherit a Swift class in Objective-C?

Swift classes that are inherited from OBJC classes are bridged automatically. That means any class inherited from, for example, UIViewController is automatically seen in the OBJC runtime. If you're creating a class that doesn't inherit from anything, then make it an NSObject subclass, as you would in OBJC.

Does Apple use Swift or Objective-C?

Objective-C is an object-oriented programming language used by Apple since the 90. It combines the advantages of two earlier languages - C and Smalltalk.

What is Objective-C ID in Swift?

In Swift 3, the id type in Objective-C now maps to the Any type in Swift, which describes a value of any type, whether a class, enum, struct, or any other Swift type.


1 Answers

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.

like image 67
Martin R Avatar answered Sep 19 '22 14:09

Martin R