Get class name of UIViewController in swift
How to get class name of UIViewController
Class in swift
In Objective C, we can do something like this :
self.appDelegate = (shAppDelegate *)[[UIApplication sharedApplication] delegate];
UIViewController *last_screen = self.appDelegate.popScreens.lastObject ;
if(last_screen.class != self.navigationController.visibleViewController.class){
//.......
}
but in swift I tried like this
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let last_screen = appDelegate.popScreens?.lastObject as UIViewController
cant do this.
if last_screen.class != self.navigationController.visibleViewController.class{
//....
}
no class method of UIViewController
i.e last screen
Solution 1:
To know your class name you can call something like this:
var className = NSStringFromClass(yourClass.classForCoder)
Solution 2:
The cleanest way without needing to know the name of your class is like this.
let name = String(describing: type(of: self))
Solution 3:
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)
Solution 4:
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!
}
}