Created
June 7, 2014 00:43
-
-
Save MartinJNash/e2bb27937711f350aa44 to your computer and use it in GitHub Desktop.
Class name to string in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person { | |
class func classString() -> String { | |
return NSStringFromClass(self) | |
} | |
} | |
Person.classString() // "_TtC11lldb_expr_06Person" |
I have also found NSStringFromClass(self.classFromCoder)
to work. Any gotchas I should know about with .classFromCoder
or .classFromKeyArchiver
?
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"
nice.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ! 👍