Skip to content

Instantly share code, notes, and snippets.

@MartinJNash
Created June 7, 2014 00:43
Show Gist options
  • Save MartinJNash/e2bb27937711f350aa44 to your computer and use it in GitHub Desktop.
Save MartinJNash/e2bb27937711f350aa44 to your computer and use it in GitHub Desktop.
Class name to string in Swift
class Person {
class func classString() -> String {
return NSStringFromClass(self)
}
}
Person.classString() // "_TtC11lldb_expr_06Person"
@remirobert
Copy link

Hi thanks for your gist it' s very helpful.
there is several way to get the name 👍
class_getName(self)
object_getClassName(self)

For parse the result, i split the string with number and i keep the last part.
Do you have an other way ?
Good job ! 👍

@jpotts18
Copy link

I have also found NSStringFromClass(self.classFromCoder) to work. Any gotchas I should know about with .classFromCoder or .classFromKeyArchiver?

@cooler333
Copy link

import UIKit


protocol TypeName: AnyObject {
    static var typeName: String { get }
}

// Swift Objects
extension TypeName {
    static var typeName: String {
        let type = String(describing: self)
        return type
    }
}

// Bridge to Obj-C
extension NSObject: TypeName {
    class var typeName: String {
        let type = String(describing: self)
        return type
    }
}


class MyViewController: UIViewController { }

class SwiftClass: TypeName { }
class MySwiftClass: SwiftClass { }


print(MyViewController.typeName)    // print "MyViewController" 

print(UIViewController.typeName)    // print "UIViewController"

let myVC = MyViewController()
print(type(of: myVC).typeName)    // print "MyViewController"

let VC = UIViewController()
print(type(of: VC).typeName)    // print "UIViewController"

print(String.typeName)
// print "NSString"
// cause: extension NSObject: TypeName
// String === NSString(Bridge)

print(SwiftClass.typeName)    // print "SwiftClass"

print(MySwiftClass.typeName)    // print "MySwiftClass"

@asilturk
Copy link

asilturk commented Aug 9, 2020

nice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment