How to get class name of UIViewController
Class in swift
In Objective C, we can do something like this :
self.appDelegate = (shAppDeleg
A simple way in swift 3 is to write the below code:
for instances:
let className = String(describing: self)
for classes:
let className = String(describing: YourViewController.self)
The property is called dynamicType
in Swift.
Expanding on juangdelvalle's answer.
I added this as an extension so that it's reusable and easier to call from any view controller. Also in some cases NSStringFromClass
in Swift returns a string in the format like this:
< project name >.viewControllerClassName.
This extension property is modified to get rid of the project name prefix and return only the class name.
extension UIViewController {
var className: String {
NSStringFromClass(self.classForCoder).components(separatedBy: ".").last!
}
}
Use String.init(describing: self.classForCoder)
example:
let viewControllerName = String.init(describing: self.classForCoder)
print("ViewController Name: \(viewControllerName)")
The cleanest way without needing to know the name of your class is like this.
let name = String(describing: type(of: self))
How about:
extension NSObject {
static var stringFromType: String? {
return NSStringFromClass(self).components(separatedBy: ".").last
}
var stringFromInstance: String? {
return NSStringFromClass(type(of: self)).components(separatedBy: ".").last
}
}