MeloS
MeloS

Reputation: 7938

Swift, a function defined in super class that returns the class name of subclass when called from a subclass object

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?

Upvotes: 1

Views: 963

Answers (3)

werediver
werediver

Reputation: 4757

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

Upvotes: 1

Martin R
Martin R

Reputation: 539775

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.

Upvotes: 1

Antonio
Antonio

Reputation: 72760

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.

Upvotes: 0

Related Questions