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?

3
  • possible duplicate of Get class name of object as string in Swift Commented Apr 10, 2015 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 Commented Apr 10, 2015 at 16:19
  • 2
    NSStringFromClass() works in Swift as well. See stackoverflow.com/a/27112385/1187415 for an example. Commented Apr 10, 2015 at 16:20

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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 

Comments

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.

1 Comment

Yes, you are right, I need to get the name from a type instead of an instance

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.