Swift 通过字符串创建类

import UIKit

class RootViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let name = "MainViewController"
        //动态获取命名空间
        let namespace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        print(namespace)
        //注意工程中必须有相关的类,否则程序会crash
        let class:AnyObject = NSClassFromString(namespace + "." + name)!
        print(class)
        // 告诉编译器它的真实类型
        let viewControllerClass = class as! UIViewController.Type
        let viewController = viewControllerClass.init()
        print(viewController)
    }
}

你可能感兴趣的:(Swift 通过字符串创建类)