Bernd
Bernd

Reputation: 11533

Get class name of object as string in Swift

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?

Upvotes: 444

Views: 332556

Answers (30)

Ashvin
Ashvin

Reputation: 9027

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

Upvotes: 17

DEEPAK KUMAR
DEEPAK KUMAR

Reputation: 361

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
}

Upvotes: 3

Rudolf Adamkovič
Rudolf Adamkovič

Reputation: 31486

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.

Upvotes: 711

Abdelaziz Elrashed
Abdelaziz Elrashed

Reputation: 743

Swift 5.2:

String(describing: type(of: self))

Upvotes: 43

nahung89
nahung89

Reputation: 8105

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

Upvotes: 167

Victor Kushnerov
Victor Kushnerov

Reputation: 3974

Swift 5.1

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

print("\(Self.self)")

Upvotes: 24

mauricioconde
mauricioconde

Reputation: 5142

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!.

Upvotes: 231

dinesh sharma
dinesh sharma

Reputation: 617

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 :)

Upvotes: 2

Ivan Tkachenko
Ivan Tkachenko

Reputation: 506

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

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

Upvotes: 4

Blazej SLEBODA
Blazej SLEBODA

Reputation: 9935

Swift 5

 NSStringFromClass(CustomClass.self)

Upvotes: 4

Ale Mohamad
Ale Mohamad

Reputation: 392

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

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

Upvotes: 6

Gurjit Singh
Gurjit Singh

Reputation: 1913

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"

Upvotes: 20

陈方涛
陈方涛

Reputation: 191

You can try this way:

self.classForCoder.description()

Upvotes: 19

Adam
Adam

Reputation: 4848

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

Upvotes: 25

Siddharth Bhatt
Siddharth Bhatt

Reputation: 613

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.

Upvotes: 9

Makalele
Makalele

Reputation: 7551

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 :)

Upvotes: -1

sethfri
sethfri

Reputation: 1327

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".

Upvotes: 29

Darkwonder
Darkwonder

Reputation: 1315

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

Upvotes: 4

Misha Karpenko
Misha Karpenko

Reputation: 2186

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()))"

Upvotes: 15

Lumialxk
Lumialxk

Reputation: 6379

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

Upvotes: 3

bob
bob

Reputation: 751

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

Upvotes: 1

werediver
werediver

Reputation: 4757

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

Upvotes: 34

Thanh Vũ Trần
Thanh Vũ Trần

Reputation: 790

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

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

Upvotes: 3

Exception
Exception

Reputation: 785

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 ?? ""
    }
}

Upvotes: 9

slim
slim

Reputation: 4040

Swift 3.0

String(describing: MyViewController.self)

Upvotes: 32

Troy
Troy

Reputation: 5409

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

Upvotes: 6

Alexander Khitev
Alexander Khitev

Reputation: 6861

I use it in Swift 2.2

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

Upvotes: 0

Paul Ardeleanu
Paul Ardeleanu

Reputation: 6700

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

Upvotes: 10

drawnonward
drawnonward

Reputation: 53689

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;
}

Upvotes: 4

Jernej Strasner
Jernej Strasner

Reputation: 4620

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

let name = _stdlib_getDemangledTypeName(myViewController)

Upvotes: 13

Related Questions