我尝试过多种方法使用字符串创建一个类的实例,但在Swift 3中都无法正常工作。
以下是我尝试过且在Swift 3之前版本中不起作用的解决方案:
- 将类设置为Objective-C类
@objc(customClass)
class customClass {
...
}
//Error here: cannot convert value of type 'AnyClass?' to expected argument type 'customClass'
let c: customClass = NSClassFromString("customClass")
- 使用NSString值指定类(使用和不使用@objc属性)
@objc(customClass)
class customClass {
...
}
//Error here: cannot convert value of type 'String' to expected argument type 'AnyClass' (aka 'AnyObject.Type')
var className = NSStringFromClass("customClass")
let c: customClass = NSClassFromString(className)
我做的事情不对,但在网上找不到任何解决方案。
如何在Swift 3中使用字符串创建类的实例?
Swift3
中实现这一点,因为那个问题的答案在我的Swift3
代码中不起作用。 - Danoram