Get class name of object as string in Swift

SwiftReflectionTypeof

Swift Problem Overview


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?

Swift Solutions


Solution 1 - Swift

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.

Solution 2 - Swift

UPDATED TO SWIFT 5

We can get pretty descriptions of type names using the instance variable through the String initializer and create new objects of a certain class

Like, for example print(String(describing: type(of: object))). Where object can be an instance variable like array, a dictionary, an Int, a NSDate, etc.

Because NSObject is the root class of most Objective-C class hierarchies, you could try to make an extension for NSObject to get the class name of every subclass of NSObject. Like this:

extension NSObject {
    var theClassName: String {
        return NSStringFromClass(type(of: self))
    }
}

Or you could make a static funcion whose parameter is of type Any (The protocol to which all types implicitly conform) and returns the class name as String. Like this:

class Utility{
    class func classNameAsString(_ obj: Any) -> String {
        //prints more readable results for dictionaries, arrays, Int, etc
        return String(describing: type(of: obj))
    }
} 

Now you can do something like this:

class ClassOne : UIViewController{ /* some code here */ }
class ClassTwo : ClassOne{ /* some code here */ }

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Get the class name as String
        let dictionary: [String: CGFloat] = [:]
        let array: [Int] = []
        let int = 9
        let numFloat: CGFloat = 3.0
        let numDouble: Double = 1.0
        let classOne = ClassOne()
        let classTwo: ClassTwo? = ClassTwo()
        let now = NSDate()
        let lbl = UILabel()

        print("dictionary: [String: CGFloat] = [:] -> \(Utility.classNameAsString(dictionary))")
        print("array: [Int] = [] -> \(Utility.classNameAsString(array))")
        print("int = 9 -> \(Utility.classNameAsString(int))")
        print("numFloat: CGFloat = 3.0 -> \(Utility.classNameAsString(numFloat))")
        print("numDouble: Double = 1.0 -> \(Utility.classNameAsString(numDouble))")
        print("classOne = ClassOne() -> \((ClassOne).self)") //we use the Extension
        if classTwo != nil {
            print("classTwo: ClassTwo? = ClassTwo() -> \(Utility.classNameAsString(classTwo!))") //now we can use a Forced-Value Expression and unwrap the value
        }
        print("now = Date() -> \(Utility.classNameAsString(now))")
        print("lbl = UILabel() -> \(String(describing: type(of: lbl)))") // we use the String initializer directly
    
    }
}

Also, once we can get the class name as String, we can instantiate new objects of that class:

// Instantiate a class from a String
print("\nInstantiate a class from a String")
let aClassName = classOne.theClassName
let aClassType = NSClassFromString(aClassName) as! NSObject.Type
let instance = aClassType.init() // we create a new object
print(String(cString: class_getName(type(of: instance))))
print(instance.self is ClassOne)

Maybe this helps someone out there!.

Solution 3 - Swift

Swift 5

Here is the extension to get the typeName as a variable (work with both value type or reference type).

protocol NameDescribable {
    var typeName: String { get }
    static var typeName: String { get }
}

extension NameDescribable {
    var typeName: String {
        return String(describing: type(of: self))
    }

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

How to use:

// Extend with class/struct/enum...
extension NSObject: NameDescribable {}
extension Array: NameDescribable {}
extension UIBarStyle: NameDescribable { }

print(UITabBarController().typeName)
print(UINavigationController.typeName)
print([Int]().typeName)
print(UIBarStyle.typeName)

// Out put:
UITabBarController
UINavigationController
Array<Int>
UIBarStyle

Solution 4 - Swift

Swift 3.0

String(describing: MyViewController.self)

Solution 5 - Swift

I suggest such an approach (very Swifty):

// Swift 3
func typeName(_ some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(type(of: some))"
}

// Swift 2
func typeName(some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(some.dynamicType)"
}

It doesn't use neither introspection nor manual demangling (no magic!).


Here is a demo:

// Swift 3

import class Foundation.NSObject

func typeName(_ some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(type(of: some))"
}

class GenericClass<T> {
    var x: T? = nil
}

protocol Proto1 {
    func f(x: Int) -> Int
}


@objc(ObjCClass1)
class Class1: NSObject, Proto1 {
    func f(x: Int) -> Int {
        return x
    }
}

struct Struct1 {
    var x: Int
}

enum Enum1 {
    case X
}

print(typeName(GenericClass<Int>.self)) // GenericClass<Int>
print(typeName(GenericClass<Int>()))  // GenericClass<Int>

print(typeName(Proto1.self)) // Proto1

print(typeName(Class1.self))   // Class1
print(typeName(Class1())) // Class1
print(typeName(Class1().f)) // (Int) -> Int

print(typeName(Struct1.self)) // Struct1
print(typeName(Struct1(x: 1))) // Struct1
print(typeName(Enum1.self)) // Enum1
print(typeName(Enum1.X)) // Enum1

Solution 6 - Swift

Swift 5.2:

String(describing: type(of: self))

Solution 7 - Swift

If you have type Foo, the following code will give you "Foo" in Swift 3 and Swift 4:

let className = String(describing: Foo.self) // Gives you "Foo"

The problem with most of the answers on here are that they give you "Foo.Type" as the resulting string when you don't have any instance of the type, when what you really want is just "Foo". The following gives you "Foo.Type", as mentioned in a bunch of the other answers.

let className = String(describing: type(of: Foo.self)) // Gives you "Foo.Type"

The type(of:) part is unnecessary if you just want "Foo".

Solution 8 - Swift

In Swift 4.1 and now Swift 4.2 :

import Foundation

class SomeClass {
    class InnerClass {
        let foo: Int

        init(foo: Int) {
            self.foo = foo
        }
    }

    let foo: Int

    init(foo: Int) {
        self.foo = foo
    }
}

class AnotherClass : NSObject {
    let foo: Int

    init(foo: Int) {
        self.foo = foo
        super.init()
    }
}

struct SomeStruct {
    let bar: Int

    init(bar: Int) {
        self.bar = bar
    }
}

let c = SomeClass(foo: 42)
let s = SomeStruct(bar: 1337)
let i = SomeClass.InnerClass(foo: 2018)
let a = AnotherClass(foo: 1<<8)

If you don't have an instance around:

String(describing: SomeClass.self) // Result: SomeClass
String(describing: SomeStruct.self) // Result: SomeStruct
String(describing: SomeClass.InnerClass.self) // Result: InnerClass
String(describing: AnotherClass.self) // Result: AnotherClass

If you do have an instance around:

String(describing: type(of: c)) // Result: SomeClass
String(describing: type(of: s)) // Result: SomeStruct
String(describing: type(of: i)) // Result: InnerClass
String(describing: type(of: a)) // Result: AnotherClass

Solution 9 - Swift

Swift 5.1

You can get class, struct, enum, protocol and NSObject names though Self.self.

print("\(Self.self)")

Solution 10 - Swift

To get name of a Swift class from an object, e.g. for var object: SomeClass(), use

String(describing: type(of: object))

To get name of a Swift class from a class type, e.g. SomeClass, use:

String(describing: SomeClass.self)

Output:

> "SomeClass"

Solution 11 - Swift

You can try this way:

self.classForCoder.description()

Solution 12 - Swift

To get the type name as a string in Swift 4 (I haven't checked the earlier versions), just use string interpolation:

"\(type(of: myViewController))"

You can use .self on a type itself, and the type(of:_) function on an instance:

// Both constants will have "UIViewController" as their value
let stringFromType = "\(UIViewController.self)"
let stringFromInstance = "\(type(of: UIViewController()))"

Solution 13 - Swift

You can use the Swift standard library function called _stdlib_getDemangledTypeName like this:

let name = _stdlib_getDemangledTypeName(myViewController)

Solution 14 - Swift

One can also use mirrors:

let vc = UIViewController()

String(Mirror(reflecting: vc).subjectType)

NB: This method can also be used for Structs and Enums. There is a displayStyle that gives an indication of what type of the structure:

Mirror(reflecting: vc).displayStyle

The return is an enum so you can:

Mirror(reflecting: vc).displayStyle == .Class

Solution 15 - Swift

Swift 3.0: You can create an extension like this one.. It gives back the class name without the project name

extension NSObject {
    var className: String {
        return NSStringFromClass(self as! AnyClass).components(separatedBy: ".").last ?? ""
    }

    public class var className: String {
        return NSStringFromClass(self).components(separatedBy: ".").last ?? ""
    }
}

Solution 16 - Swift

You can extend NSObjectProtocol in Swift 4 like this :

import Foundation

extension NSObjectProtocol {

    var className: String {
        return String(describing: Self.self)
    }
}

This will make calculated variable className available to ALL classes. Using this inside a print() in CalendarViewController will print "CalendarViewController" in console.

Solution 17 - Swift

To get class name as String declare your class as following

@objc(YourClassName) class YourClassName{}

And get class name using following syntax

NSStringFromClass(YourClassName)

Solution 18 - Swift

I've been looking for this answer off and on for a while. I use GKStateMachine and like to observe state changes and wanted an easy way to see just the class name. I'm not sure if it's just iOS 10 or Swift 2.3, but in that environment, the following does exactly what I want:

let state:GKState?
print("Class Name: \(String(state.classForCoder)")

// Output:    
// Class Name: GKState

Solution 19 - Swift

You can get the name of the class doing something like:

class Person {}
String(describing: Person.self)

Solution 20 - Swift

Try reflect().summary on Class self or instance dynamicType. Unwrap optionals before getting dynamicType otherwise the dynamicType is the Optional wrapper.

class SampleClass { class InnerClass{} }
let sampleClassName = reflect(SampleClass.self).summary;
let instance = SampleClass();
let instanceClassName = reflect(instance.dynamicType).summary;
let innerInstance = SampleClass.InnerClass();
let InnerInstanceClassName = reflect(innerInstance.dynamicType).summary.pathExtension;
let tupleArray = [(Int,[String:Int])]();
let tupleArrayTypeName = reflect(tupleArray.dynamicType).summary;

The summary is a class path with generic types described. To get a simple class name from the summary try this method.

func simpleClassName( complexClassName:String ) -> String {
	var result = complexClassName;
	var range = result.rangeOfString( "<" );
	if ( nil != range ) { result = result.substringToIndex( range!.startIndex ); }
	range = result.rangeOfString( "." );
	if ( nil != range ) { result = result.pathExtension; }
	return result;
}

Solution 21 - Swift

The above solutions didn't work for me. The produced mostly the issues mention in several comments:

> MyAppName.ClassName

or

> MyFrameWorkName.ClassName

This solutions worked on XCode 9, Swift 3.0:

I named it classNameCleaned so it is easier to access and doesn't conflict with future className() changes:

extension NSObject {

static var classNameCleaned : String {

	let className = self.className()
	if className.contains(".") {
		let namesArray = className.components(separatedBy: ".")
		return namesArray.last ?? className
	} else {
		return self.className()
	}
	
}

}

Usage:

NSViewController.classNameCleaned
MyCustomClass.classNameCleaned

Solution 22 - Swift

Swift 5:

Way 1:

print("Class: \(String(describing: self)), Function: \(#function), line: \(#line)")

Output:

Class: <Test.ViewController: 0x7ffaabc0a3d0>, Function: viewDidLoad(), line: 15

Way 2:

print("Class: \(String(describing: type(of: self))), Function: \(#function), line: \(#line)")

Output:

Class: ViewController, Function: viewDidLoad(), line: 16

Solution 23 - Swift

Swift 3.0 (macOS 10.10 and later), you can get it from className

self.className.components(separatedBy: ".").last!

Solution 24 - Swift

I tried type(of:...) in Playground with Swift 3. This is my result. This is the code format version.

print(String(describing: type(of: UIButton.self)))
print(String(describing: type(of: UIButton())))
UIButton.Type
UIButton

Solution 25 - Swift

Swift 5

 NSStringFromClass(CustomClass.self)

Solution 26 - Swift

This kind of example for class var. Don't include the name of bundle.

extension NSObject {
    class var className: String {
        return "\(self)"
    }
}

Solution 27 - Swift

Swift 5.1 :-

You can also use generic function for get class name of object as string

struct GenericFunctions {
 static func className<T>(_ name: T) -> String {
        return "\(name)"
    }

}

Call this function by using following:-

let name = GenericFunctions.className(ViewController.self)

Happy Coding :)

Solution 28 - Swift

If you don't like the mangled name, you can dictate your own name:

@objc(CalendarViewController) class CalendarViewController : UIViewController {
    // ...
}

However, it would be better in the long run to learn to parse the mangled name. The format is standard and meaningful and won't change.

Solution 29 - Swift

Sometimes the other solutions will give a non useful name depending on what object you are trying to look at. In that case you can get the class name as a string using the following.

String(cString: object_getClassName(Any!))

⌘ click the function in xcode to see some related methods that are fairly useful. or check here https://developer.apple.com/reference/objectivec/objective_c_functions

Solution 30 - Swift

This solution will work for all the classes

Swift 5 solution:

extension NSObject {
  var className: String {
    return String(describing: type(of: self))
  }

  class var className: String {
    return String(describing: self)
  }
}

USAGE:

class TextFieldCell: UITableVIewCell {
}

class LoginViewController: UIViewController {
  let cellClassName = TextFieldCell.className
}

Solution 31 - Swift

I use it in Swift 2.2

guard let currentController = UIApplication.topViewController() else { return }
currentController.classForCoder.description().componentsSeparatedByString(".").last!

Solution 32 - Swift

In my case String(describing: self) returned something like:

> < My_project.ExampleViewController: 0x10b2bb2b0>

But I'd like to have something like getSimpleName on Android.

So I've created a little extension:

extension UIViewController {
    
    func getSimpleClassName() -> String {
        let describing = String(describing: self)
        if let dotIndex = describing.index(of: "."), let commaIndex = describing.index(of: ":") {
            let afterDotIndex = describing.index(after: dotIndex)
            if(afterDotIndex < commaIndex) {
                return String(describing[afterDotIndex ..< commaIndex])
            }
        }
        return describing
    }

}

And now it returns:

> ExampleViewController

Extending NSObject instead of UIViewController should also work. Function above is also fail-safe :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBerndView Question on Stackoverflow
Solution 1 - SwiftRudolf AdamkovičView Answer on Stackoverflow
Solution 2 - SwiftmauriciocondeView Answer on Stackoverflow
Solution 3 - Swiftnahung89View Answer on Stackoverflow
Solution 4 - SwiftslimView Answer on Stackoverflow
Solution 5 - SwiftwerediverView Answer on Stackoverflow
Solution 6 - SwiftAbdelaziz ElrashedView Answer on Stackoverflow
Solution 7 - SwiftsethfriView Answer on Stackoverflow
Solution 8 - SwiftAdamView Answer on Stackoverflow
Solution 9 - SwiftVictor KushnerovView Answer on Stackoverflow
Solution 10 - SwiftGurjit SinghView Answer on Stackoverflow
Solution 11 - Swift陈方涛View Answer on Stackoverflow
Solution 12 - SwiftMisha KarpenkoView Answer on Stackoverflow
Solution 13 - SwiftJernej StrasnerView Answer on Stackoverflow
Solution 14 - SwiftPaul ArdeleanuView Answer on Stackoverflow
Solution 15 - SwiftExceptionView Answer on Stackoverflow
Solution 16 - SwiftSiddharth BhattView Answer on Stackoverflow
Solution 17 - SwiftMoin UddinView Answer on Stackoverflow
Solution 18 - SwiftTroyView Answer on Stackoverflow
Solution 19 - SwiftAle MohamadView Answer on Stackoverflow
Solution 20 - SwiftdrawnonwardView Answer on Stackoverflow
Solution 21 - SwiftDarkwonderView Answer on Stackoverflow
Solution 22 - SwiftAshvin AView Answer on Stackoverflow
Solution 23 - SwiftThanh Vũ TrầnView Answer on Stackoverflow
Solution 24 - SwiftLumialxkView Answer on Stackoverflow
Solution 25 - SwiftBlazej SLEBODAView Answer on Stackoverflow
Solution 26 - SwiftIvan TkachenkoView Answer on Stackoverflow
Solution 27 - Swiftdinesh sharmaView Answer on Stackoverflow
Solution 28 - SwiftmattView Answer on Stackoverflow
Solution 29 - SwiftbobView Answer on Stackoverflow
Solution 30 - SwiftDEEPAK KUMARView Answer on Stackoverflow
Solution 31 - SwiftAlexander KhitevView Answer on Stackoverflow
Solution 32 - SwiftMakaleleView Answer on Stackoverflow