【发布时间】:2018-09-23 21:40:50
【问题描述】:
所以我想知道是否可以将类型保存在变量中,以便稍后在同一个函数中使用。
我的代码如下:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let object = array.item(at: indexPath.row) else {
fatalError("Could not retrieve the table object")
}
if object.displayOnLeft {
guard let cell = tableView.dequeueReusableCell(withIdentifier: LeftSidedCell.className, for: indexPath) as? LeftSidedCell else {
fatalError("Could not dequeue the left sided cell")
}
cell.object = object
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: RightSidedCell.className, for: indexPath) as? RightSidedCell else {
fatalError("Could not dequeue the right sided cell")
}
cell.object = object
return cell
}
}
但我认为这实际上很笨拙,因为 if 和 else 中的内容本质上是相同的,只是单元格的类型不同。
我理想的算法基本上是:
var type
if object.displayOnLeft {
type = LeftSidedCell
} else {
type = RightSidedCell
}
//Dequeue Cell with type
我知道这里有几个问题,首先,我不能在没有类型的情况下声明一个变量,而且我一开始不确定将它分配给什么类型。其次,检索类的类型也没有取得成果。
我已经尝试将它作为属性存储在对象中,以及在我的自定义对象中的函数中返回它,以及以下的一些变体:
func getTypeOfCell<T:TranslationCellProtocol>() -> T.Type {
if displayOnLeft {
return LeftSidedCell.self
} else {
return RightSidedCell.self
}
}
无论如何,我不确定这是否可能,或者我是否对某个概念有根本的误解,但我们将不胜感激。
谢谢。
【问题讨论】:
-
简单的一种衬线解决方案是
let type = object.displayOnLeft ? LeftSidedCell.self : RightSidedCell.self,然后使用type.className -
@Kamran 虽然您的解决方案可能是最简单的解决方案,但编译器不允许我使用 type.className 进行强制转换