Swift 获取运行时不工作的单元格的动态类型

Swift 获取运行时不工作的单元格的动态类型,swift,types,Swift,Types,我在Swift项目中获得了使用自定义单元格的示例: let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! HeadlineTableViewCell 但在我的项目中,我实际上有一个名为“菌丝体”的定制细胞数组 所以我想我可以把它改成: let cell = tableView.dequeueReusableCell(withIde

我在Swift项目中获得了使用自定义单元格的示例:

let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
                    as! HeadlineTableViewCell
但在我的项目中,我实际上有一个名为“菌丝体”的定制细胞数组

所以我想我可以把它改成:

let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
                    as! type(of:allCells[indexPath.row])
但是没有。编译器对此表示不满:

Cannot create a single-element tuple with an element label

也许这是愚蠢的,但我不明白为什么它不起作用。有人能帮我澄清一下到底发生了什么吗?

您提出的问题是某种语法错误,在您提供的代码中是看不到的

但是,请使用泛型:

定义如下:

protocol Reusable: UIView {
    static var identifier: String { get }
}
myTableView.dequeueReusableCell(type: HeadlineTableViewCell.self, for: indexPath)
将其扩展到
UITableViewCell

extension Reusable where Self: UITableViewCell {
    static var identifier: String {
        return String(describing: self)
    }
}
使单元格与之一致:

extension HeadlineTableViewCell: Reusable {}
将此扩展添加到
UITableView

extension UITableView {
    func dequeueReusableCell<T: UITableViewCell & Reusable>(type cellType: T.Type, for indexPath: IndexPath) -> T {
        return dequeueReusableCell(withIdentifier: cellType.identifier, for: indexPath) as! T
    }
}

这将同时进行出列和强制转换

我假设所有单元格是一个包含表视图单元格列表的数组,但单元格属于不同的类类型

您正在使用的这一行不能以您试图使用它的方式使用

type(of:allCells[indexPath.row])
这就是为什么你会出错。此函数返回objects元类型,您不能以上面尝试的方式使用该结果。你可能也应该研究一下optionals是如何工作的,以及如何打开它们,因为你尝试这样做的方式是行不通的。下面这行代码可以正常工作,但使用type(of:)语法展开将不起作用:

let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! HeadlineTableViewCell
老实说,使用阵列存储tableViewCells的整个体系结构都是错误的,我甚至不确定您这样做是为了实现什么,但我几乎可以100%地说这是一个非常糟糕的想法。相反,数组应该存储tableViewCell将要显示的数据

老实说,如果我是你,我会查阅一本关于表视图的教程,因为我觉得这里有很多关于表视图如何工作的误解,这导致了你编写的代码和你遇到的问题


查看本教程。它应该能帮助你更好地理解事物是如何工作的。

我在我的应用程序中使用了类似的东西,这就是我解决这个问题的方法

    extension UITableViewCell {
         @objc func configure(_ data: AnyObject) {}
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = info.sectionInfo[indexPath.section].data[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: data.identifier.rawValue, for: indexPath)
        cell.configure(data as AnyObject)
        return cell
    }

    class DefaultCell: UITableViewCell {

    override func configure(_ data: AnyObject) {
        guard let data = data as? MyDesiredClass
            else {
                return
        }
        // do smth
    }

}
在这种情况下,您不需要直接传递单元格类型,因为任何单元格都包含configure func,您可以在其中填充所有字段