我想将一组类类型作为参数传递给函数,我该怎么做?
码:
let classList = [Class1.self, Class2.self, Class3.self]
myFunction(classList) // how would I write the parameter for this?
目标:我创建了一个UITableView
扩展名来缩短注册笔尖,您可以使用来调用它tableView.register(CellClass.self)
。功能签名是func register<T>(_ cellType: T.Type)
鉴于此,我试图创建一个寄存器单元功能,在其中我想执行以下操作:
func registerCells(classTypes: [XXXX]) {
classTypes { (classType) in
tableView.register(YYYY)
}
}
并使用 tableView.resigterCells([Class1.self, Class2.self, Class3.self])
我不确定在Swift中是否可行。请指教 :)
您当然可以这样做:
func registerOneCellType(_ type: UITableViewCell.Type) {}
func registerCellTypes(_ types:[UITableViewCell.Type]) {
for type in types {
registerOneCellType(type)
}
}
class CellType1: UITableViewCell {}
class CellType2: UITableViewCell {}
registerCellTypes([CellType1.self, CellType2.self])
但是你知道吗?我不会!我将传递实际的单元格对象并采用它们的类型,然后从那里开始。当您传递实例而不是类型时,Swift会更加令人愉悦。
func registerOneType(ofCell: UITableViewCell) {}
func registerTypes(ofCells: [UITableViewCell]) {
for cell in ofCells {
registerOneType(ofCell: cell)
}
}
class CellType1: UITableViewCell {}
class CellType2: UITableViewCell {}
registerTypes(ofCells: [CellType1(), CellType2()])
在内部,registerOneType
我会打电话type(of:)
给您获取类型,然后离开。请注意,就我所知,这里不需要泛型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句