我尝试使用字符串以多种方式创建类的实例,但没有一个在Swift 3中工作.
以下是我尝试过的无法正常工作的Swift 3解决方案
– 使课程成为一个客观的课程
@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中使用字符串创建类的实例?
你可以试试这个:
原文链接:https://www.f2er.com/swift/320196.htmlfunc stringClassFromString(_ className: String) -> AnyClass! { /// get namespace let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String; /// get 'anyClass' with classname and namespace let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!; // return AnyClass! return cls; }
像这样使用func:
class customClass: UITableView { } let myclass = stringClassFromString("customClass") as! UITableView.Type let instance = myclass.init()