在表格视图单元格上做守卫有什么好处吗?

鸭子

我见过有人在表视图委托中编写此代码

override func tableView(_ tableView: UITableView,
                      cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! SuitCell? else {
      fatalError()
    }
  ...
}

现在考虑这个其他代码

  override func tableView(_ tableView: UITableView,
                          cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! SuitCell

    ...
}

如果单元没有出列,两个代码不会在同一行崩溃吗?

有什么区别吗?我没有看到它。

保威11

dequeueReusableCell(withIdentifier:)可以nil在重用池中没有单元格的情况下返回(即首次显示 tableview 时)。当它返回时nil,您有责任实例化适当类型的单元格。

因此,这段代码:

guard let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! SuitCell? else {
  fatalError()
}

说“如果您从重用池中获得一个单元格并且它不是SuitCell, 崩溃的实例,但是nil可以”(注意强制转换为可选)

虽然这段代码:

let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! SuitCell

说“如果你没有得到一个实例就会崩溃SuitCell,或者你得到了nil”,所以当 tableview 第一次显示时它会崩溃。

dequeueReusableCell(withIdentifier:)真的不再使用了。您将使用较新的(但自 iOS 6 以来仍然存在)dequeueReusableCell(withIdentifier:,for:)变体,因为它总是返回一个单元格,并且您可以期望它是正确的类(或者您会在开发过程中很快发现您的问题):

let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! SuitCell

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章