Question:

found nil while unwrapping an Optinal value

Code:

if let cls = NSClassFromString("TestViewController") as? UIViewController.Type { let vc = cls.init() navigationController? .pushViewController(vc, animated: true) }Copy the code

However, the execution does not enter the if judgment. Swift is quite different from OC. When converting from string to type, if the type is custom, you need to add the name of your project before the type string

The solution:

Define a method that returns the name of the app

func getAPPName() -> String {
    guard let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else { return "" }
    return appName
}
Copy the code

And then this is it:

if let cls = NSClassFromString(getAPPName() + "." + "TestViewController") as? UIViewController.Type { let vc = cls.init() navigationController? .pushViewController(vc, animated: true) }Copy the code

Note: Don't forget to add "."