如何在swift 3中从字符串创建类的实例

前端之家收集整理的这篇文章主要介绍了如何在swift 3中从字符串创建类的实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试使用字符串以多种方式创建类的实例,但没有一个在Swift 3中工作.

以下是我尝试过的无法正常工作的Swift 3解决方

– 使课程成为一个客观的课程

  1. @objc(customClass)
  2. class customClass {
  3. ...
  4. }
  5.  
  6. //Error here: cannot convert value of type 'AnyClass?' to expected argument type 'customClass'
  7. let c: customClass = NSClassFromString("customClass")

– 使用NSString值指定类(使用和不使用@objc属性)

  1. @objc(customClass)
  2. class customClass {
  3. ...
  4. }
  5.  
  6. //Error here: cannot convert value of type 'String' to expected argument type 'AnyClass' (aka 'AnyObject.Type')
  7. var className = NSStringFromClass("customClass")
  8.  
  9. let c: customClass = NSClassFromString(className)

我做的不对,但没有在网上找到任何解决方案.

如何在Swift 3中使用字符串创建类的实例?

你可以试试这个:
  1. func stringClassFromString(_ className: String) -> AnyClass! {
  2.  
  3. /// get namespace
  4. let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
  5.  
  6. /// get 'anyClass' with classname and namespace
  7. let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!;
  8.  
  9. // return AnyClass!
  10. return cls;
  11. }

像这样使用func:

  1. class customClass: UITableView {
  2.  
  3. }
  4. let myclass = stringClassFromString("customClass") as! UITableView.Type
  5. let instance = myclass.init()

猜你在找的Swift相关文章