iOS Swift 获取类名和动态创建加载类

获取类名

中文网络上搜出来的一堆都是错误的,第一种通过读取 CFBundleExecutable 作为命名空间的,那其它模块的同名怎么处理?第二种继承 NSObject 通过 description() 获取,那不继承的怎么获取?

class MyViewModel {}
// 获取带命名空间类名
print(String(reflecting: MyViewModel.self))
// 获取不带命名空间类名
print(String(describing: MyViewModel.self))
// 类实例获取类名
print(String(reflecting: type(of: MyViewModel())))
print(String(describing: type(of: MyViewModel())))

动态创建类

找到的基本都是 NSClassFromString 根据类名创建,同样的那不继承 NSObject 就不能创建了吗?

public protocol ViewModelType {
    init()
}

public protocol ControllerViewModelType {
    init(controller: UIViewController)
}

func create<T>(controller: UIViewController) -> T {
    let type = T.self
    if let type = type as? ControllerViewModelType.Type {
        return type.init(controller: controller) as! T
    } else if let type = type as? ViewModelType.Type {
        return type.init() as! T
    } else if let type = type as? NSObject.Type {
        return type.init() as! T
    } else {
        fatalError("init() has not been implemented")
    }
}

参考

keyword: swift dynamic create object
DynamicInit.swift

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容