Get name of instantiated class

I am trying to make a little MVP for the company I am working for (new job) and I am trying to dynamically load view controllers so I thought to add the following extension as listed below.

Only when I try to get the name of any class, e.g. UINavigationController it’s returning NSObject for example in a snippet like:

let navController = UINavigationController()
Foundation.NSLog("LOG: Class Name: \(navController.nameOfClass)")

I am wondering what I am doing wrong? I would expect it would return whatever the class name is e.g. here UINavigationController and when I would inherit from final class BlahVC: UIViewController etc I would expect it to return BlahVC.

The problem is that when I do something like:

extension UIViewController {
    private class func instantiateControllerInStoryboard<T: UIViewController>(_ storyboard: UIStoryboard, identifier: String) -> T {
        return storyboard.instantiateViewController(identifier: identifier) as! T
    class func controllerInStoryboard(_ storyboard: UIStoryboard, identifier: String) -> Self {
        return storyboard.instantiateViewController(identifier: identifier)
    class func controllerInStoryboard(_ storyboard: UIStoryboard) -> Self {
        return controllerInStoryboard(storyboard, identifier: self.nameOfClass)
    class func controllerFromStoryboard(_ storyboard: Storyboards) -> Self {
        return controllerInStoryboard(UIStoryboard(name: storyboard.rawValue, bundle: nil), identifier: self.nameOfClass)
public extension NSObject {
    class public var nameOfClass: String {
        return NSStringFromClass(self).componentsSeparated(by: ".").lastObject!

Please find a reproducible project attached :slight_smile: (138.8 KB)

Odd. I’ll check in the morning. What does self.class.description return?

I have tried return self.class.description.componentsSeparated(by: ".").lastObject! and it gives the same behaviour of:

2019-09-24 00:28:12.727030+0100 App[52526:11825035] navController: NSObject
2019-09-24 00:28:12.727190+0100 App[52526:11825035] viewController: NSObject
2019-09-24 00:28:12.727334+0100 App[52526:11825035] myVC: NSObject
2019-09-24 00:28:12.728211+0100 App[52526:11825035] altVC: NSObject

weird. BTW, why .componentsSeparated(by: ".").lastObject!? Cocoa class names don’t have dots.

1 Like

Fair question, can’t remember anymore :slight_smile:
Have to admit I probably copied it from Stackoverflow or Github :angel: