獲取類名
中文網(wǎng)絡(luò)上搜出來(lái)的一堆都是錯(cuò)誤的垒玲,第一種通過(guò)讀取 CFBundleExecutable
作為命名空間的纳猫,那其它模塊的同名怎么處理恕出?第二種繼承 NSObject
通過(guò) description()
獲取蔼卡,那不繼承的怎么獲韧蜕 述么?
class MyViewModel {}
// 獲取帶命名空間類名
print(String(reflecting: MyViewModel.self))
// 獲取不帶命名空間類名
print(String(describing: MyViewModel.self))
// 類實(shí)例獲取類名
print(String(reflecting: type(of: MyViewModel())))
print(String(describing: type(of: MyViewModel())))
動(dòng)態(tài)創(chuàng)建類
找到的基本都是 NSClassFromString
根據(jù)類名創(chuàng)建,同樣的那不繼承 NSObject
就不能創(chuàng)建了嗎愕掏?
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