1

In Objective-C I can do this:

@interface MyManagedObjectSuperClass : NSManagedObject 
+(NSString*)entityName;
@end

@implementation
+(NSString*)entityName
{
    return NSStringFromClass([self class])
}
@end

With this base class, all my other NSManagedObjects can inherit from MyManagedObjectSuperClass. I can get the entity name by calling +entityName, since there is polymorphism, in subclasses, NSStringFromClass([self class]) returns the class name of subclass.

So my question is, can I do this in Swift?

CarmeloS
  • 7,868
  • 8
  • 56
  • 103
  • possible duplicate of [Get class name of object as string in Swift](http://stackoverflow.com/questions/24494784/get-class-name-of-object-as-string-in-swift) – bjtitus Apr 10 '15 at 16:08
  • @bjtitus it's not a duplicate, I need to get it from a type instead of an instance, and I need polymorphism – CarmeloS Apr 10 '15 at 16:19
  • 2
    `NSStringFromClass()` works in Swift as well. See http://stackoverflow.com/a/27112385/1187415 for an example. – Martin R Apr 10 '15 at 16:20

3 Answers3

1

In a class method of an NSObject subclass, both

toString(self)
NSStringFromClass(self)

return a string containing the class name (including product module name) of the actual subclass on which the method is called.

See How can I create instances of managed object subclasses in a NSManagedObject Swift extension? for an example how to extract the Core Data entity name from the full class name.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

Is this straightforward approach what you need?

class Base {

    class func typeName() -> String {
        return "\(self)"
    }

}

class X: Base {}

print(Base.typeName()) // Base
print(X.typeName()) // X
werediver
  • 4,667
  • 1
  • 29
  • 49
0

You can use dynamicType to obtain the class name (inclusive of the module name), and string interpolation to convert it to a string:

class Class1 {
    var entityName: String {
        return "\(self.dynamicType)"
    }
}

The most obvious difference is that it's an instance and not a static property/method - that's probably a limitation in your case, as I presume you want to obtain the name from the type and not an instance of it.

Antonio
  • 71,651
  • 11
  • 148
  • 165