1
UIViewController *viewController = [[NSClassFromString(viewControllerName) alloc] init];

How to convert this code of NSClassFromString to swift?

Rigel1121
  • 2,022
  • 1
  • 17
  • 24
Arun Kumar P
  • 820
  • 2
  • 12
  • 25

1 Answers1

1

You could write something like this:

if let viewController = NSClassFromString(viewControllerName) as? UIViewController.Type {
   // Do something 
}
valzevul
  • 127
  • 6
  • 2
    NSClassFromString does not work for Swift classes. In that case, you have to use full qualified name like `AppName.ClassName`. Take a look at this link: http://stackoverflow.com/questions/24570345/nsclassfromstring-always-returns-nil – Duyen-Hoa Apr 20 '15 at 08:33
  • @HoaParis yes, sure, however it works for classes inherited from NSObject (that's why for UIViewController this will work). – valzevul Apr 20 '15 at 09:45
  • That code returns the class type, not the instance. You need to still call init() on the class type. – jrc Mar 04 '16 at 11:56