如何在Swift中根据字符串创建对象? [英] How to create an object depending on a String in Swift?

查看:194
本文介绍了如何在Swift中根据字符串创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想重构的代码:

let myCell = MyCustomTableViewCell()
self.createCell(myCell, reuseIdentifierString: "myCellIdentifier")

MyCustomTableViewCell符合SetCell协议,因此可以正常工作.并且SetCell协议不是@obj_c协议.这是一个快速的协议

the MyCustomTableViewCell conforms to the SetCell protocol so it works fine. and the SetCell protocol is not an @obj_c protocol. This is a swift protocol

private func createCell<T where T:SetCell>(classType: T, reuseIdentifierString: String) -> UITableViewCell {
  var cell = _tableView.dequeueReusableCellWithIdentifier(reuseIdentifierString) as T
  cell.setText()
  return cell.getCustomCell()
}

现在我重构代码,我想根据一个字符串创建myCell,但是该字符串与我的类名完全相同.我不想使用else-if或switch-case

And now I refactor my code, I would like to create the myCell depending on a String, but the string is exactly the same as my Class name. I dont want to use else-if or switch-case

let myCell: AnyClass! = NSClassFromString("MyCustomTableViewCell")
self.createCell(myCell, reuseIdentifierString: "myCellIdentifier")

但是现在AnyClass的myCell不符合协议. 我该怎么办?

But now the myCell which is AnyClass does not conform to protocol. How can I do this?

推荐答案

您需要的代码更多.您将获得一个AnyClass而不是AnyObject.因此,您需要创建该类型的实例.您可以尝试以下方法:

You need a little more code than that. You will get an AnyClass and not an AnyObject. So you need to create an instance of that type. You could try this:

let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var theObject: NSObject! = objectType() as NSObject
var myCell:MyCell = theObject as MyCell

要使其符合您的协议,您可以尝试以下几种方法:

For letting it conform to your protocol you could try a couple of things:

1.您可以为所有符合协议的单元创建基类.并在上面的代码中使用它而不是UITableViewCell.为此,您可以使用如下代码:

protocol SetCell {
    func setcell() {}
}
class BaseUITableViewCell : UITableViewCell, SetCell {
    func setcell() {}
}
class MyCell : BaseUITableViewCell {
    override func setcell() {}
}

let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var theObject: NSObject! = objectType() as NSObject
var myCell:BaseUITableViewCell = theObject as BaseUITableViewCell

2.您可以使用扩展名来扩展UITableViewCell,例如添加一个空扩展名

extension UITableViewCell: SetCell {}

//编译时错误:

Declarations from extensions cannot be overridden yet

//Edwin:奇怪,在文档中.看来这是出门了...

//Edwin: Strange, this is in the documentation. So it looks like this one is out...

3.您可以定义一个符合以下协议的变量:

@objc protocol SetCell {
    func setcell() {}
}

let cellClass: AnyClass! = NSClassFromString("MyCell")
var objectType : NSObject.Type! = cellClass as NSObject.Type!
var myCell2:protocol<SetCell> = objectType() as protocol<SetCell>

这篇关于如何在Swift中根据字符串创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆