我们已经实现了一个名为
另外还有这个:
有没有一种方法可以将类类型信息与协议一致性存储在数组中,以使其正常工作?
Reusable
的协议,用于简化UITableView
注册/出列实现,适用于我们的UITableViewCell
。protocol Reusable: class {
static var defaultIdentifier: String { get }
}
extension Reusable where Self: UITableViewCell {
static var defaultIdentifier: String {
return String(describing: self)
}
}
class TestTableViewCell: UITableViewCell, Reusable { }
class AnotherTestTableViewCell: UITableViewCell, Reusable { }
然后,有一个扩展到UITableView
的类似:
extension UITableView {
func register<T: UITableViewCell & Reusable>(_: T.Type) {
register(UINib(nibName: T.defaultIdentifier, bundle: nil), forCellReuseIdentifier: T.defaultIdentifier)
}
}
以及它的使用:
let tableView: UITableView = UITableView()
tableView.register(TestTableViewCell.self)
tableView.register(AnotherTableViewCell.self)
一切正常,但我们希望将这些类型移动到数组中以进行排序。这是我们遇到问题的地方,以下代码不起作用:
let viewCells = [TestTableViewCell.self, AnotherTestTableViewCell.self]
// Without type annotation, it's [UITableViewCell.Type]
// And the error is: Instance method 'register' requires that 'UITableViewCell' conform to 'Reusable'
for viewCell in viewCells {
tableView.register(viewCell)
}
我们也尝试过:
let viewCells: [Reusable.Type] = ...
// Error: Cannot invoke 'register' with an argument list of type '(Reusable.Type)'
另外还有这个:
let viewCells: [(UITableViewCell & Reusable).Type] = ...
// Error: Instance method 'register' requires that 'UITableViewCell' conform to 'Reusable'
有没有一种方法可以将类类型信息与协议一致性存储在数组中,以使其正常工作?