Swift 将变量转换为变量类

标签 swift

我正在尝试将单元格转换为动态类类型:

struct Item {
    var cellClass: AnyClass
}


let cellClass = item.cellClass
let cell: cellClass = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)

但是,我收到错误: cellClass 不是类型

执行此操作的正确方法是什么?

最佳答案

AnyClass 定义为 AnyObject.Type,并且您无法创建 AnyObject 类型的实例,它没有公共(public)初始值设定项。 ..

但是,如果您知道所有单元格都将是 UITableViewCell 的子类型,则可以使用以下命令执行您想要的操作:

struct Item {
    var cellClass: UITableViewCell.Type
}

class Test: UITableViewCell {
    var str = ""
}

// create an instance of Item with the class Test
let i = Item(cellClass: Test.self)

// then create an instance of Test by using the instance of Item
var t = i.cellClass.init()

然后,当你询问if t is Test时,它会说true

关于Swift 将变量转换为变量类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33923804/

相关文章:

ios - Swift 分派(dispatch)到子类扩展中的重写方法

swift - 几个 "Remove View"方法后 subview 不删除

ios - 表格 View 中的搜索栏

ios - map 框 : How to change MGLFillStyleLayer "fill-outline-width"

objective-c - 如何在 Swift 中传递 Raw Json 来发布请求?

ios - 删除单元格导致崩溃

ios - 在 AppDelegate Swift 中获取本地通知的正文或标识符

swift - 间隔中的 GPS ping

swift - 快速更改标签栏未选择的图标颜色

ios - 使用 Alamofire 上传音频文件