Search code examples
swiftviewcontrollerinitclassname

Create a swift2 class from classname


I'm new in Swift.

In objective C, I pushed custom UIViewController create from its classname:

NSString *classString = "customViewController";
UIViewController *vc = [[NSClassFromString(classString) alloc] init];
[self pushViewController:vc animated:YES];

I cannot build class in swift, this doesn't work:

let myClass = NSClassFromString("customViewController") as! UIViewController.Type
let vc = myClass.init()
self.presentViewController(vc, animated: true, completion: nil)

Error : fatal error: unexpectedly found nil while unwrapping an Optional value


Solution

  • The reason it fails is that the view controller class name you have referenced (customViewController) is not fully qualified by the module name. This can be found in Interface Builder below the custom class name:

    enter image description here

    You should change the class name string to represent the fully qualified name of the view controller, for example:

    let myClass = NSClassFromString("MyProject.customViewController") as! UIViewController.Type