0

It works fine in OC:

NSString *controllerName = @"SecondViewController";
Class clazz = NSClassFromString(controllerName);
UIViewController *viewController = [[clazz alloc] init];
[self.navigationController pushViewController:viewController animated:YES];

When I use swift:

let controllerName = "SecondViewController"
let controller:AnyClass = NSClassFromString(controllerName)!
let viewController = (controller as! UIViewController.Type).init()
navigationController?.pushViewController(viewController, animated: true)

It crashed at let controller:AnyClass = NSClassFromString(controllerName)!

Any ideas?

enter image description here

Tony
  • 542
  • 3
  • 13

1 Answers1

1

Swift classes are namespaced now so instead of "SecondViewController" it'd be "AppName.SecondViewController"

    let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
    let controllerName = "SecondViewController"
    let controller:AnyClass = NSClassFromString(nameSpace + "." + controllerName)!
    let viewController = (controller as! UIViewController.Type).init()
    navigationController?.pushViewController(viewController, animated: true)
Tony
  • 542
  • 3
  • 13