Swift中字符串转化为Class的方法

Swift中字符串转化为Class的方法

在开发中有时候会根据字符串进行对应类的转化,这样我们就可以动态根据服务器返回的字段,动态的加载类,比如优酷,微博等APP会在节假日等动态的TabBar。这样可以把苹果审核的风险给排出。

在OC中根据一段字符串转化为类,可以很方便的进行,只需要使用NSClassFromString 即可

NSClassFromString(@"NewsViewController")

但是在Swift中由于命名空间的存在导致这样的转化,会有一定的麻烦,我们可以用下面的方法进行转化。

func getClass(stringName: String) -> Class {
//根据字符串获取对应的class,在Swift中不能直接使用

//Swift中命名空间的概念
guard let nameSpage = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
    print("没有命名空间")
    return
}

guard let childVcClass = NSClassFromString(nameSpage + "." + vcName) else {
    print("没有获取到对应的class")
    return
}

guard let childVcType = childVcClass as? UIViewController.Type else {
    print("没有得到的类型")
    return
}

//根据类型创建对应的对象
let vc = childVcType.init()

return vc

}

原文地址:https://www.cnblogs.com/fengtengfei/p/6104714.html