Get class name of object as string in Swift

Bernd picture Bernd · Jun 30, 2014 · Viewed 221.8k times · Source

Getting the classname of an object as String using:

object_getClassName(myViewController)

returns something like this:

_TtC5AppName22CalendarViewController

I am looking for the pure version: "CalendarViewController". How do I get a cleaned up string of the class name instead?

I found some attempts of questions about this but not an actual answer. Is it not possible at all?

Answer

Rudolf Adamkovič picture Rudolf Adamkovič · Jan 19, 2016

String from an instance:

String(describing: self)

String from a type:

String(describing: YourType.self)

Example:

struct Foo {

    // Instance Level
    var typeName: String {
        return String(describing: Foo.self)
    }

    // Instance Level - Alternative Way
    var otherTypeName: String {
        let thisType = type(of: self)
        return String(describing: thisType)
    }

    // Type Level
    static var typeName: String {
        return String(describing: self)
    }

}

Foo().typeName       // = "Foo"
Foo().otherTypeName  // = "Foo"
Foo.typeName         // = "Foo"

Tested with class, struct and enum.