我尝试使用字符串以多种方式创建类的实例,但没有一个在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中使用字符串创建类的实例?
你可以试试这个:
func 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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。