Ios 在Swift中编程自定义UITableViewCell时强制向下广播
在以下代码中:Ios 在Swift中编程自定义UITableViewCell时强制向下广播,ios,swift,cocoa-touch,Ios,Swift,Cocoa Touch,在以下代码中: let cell = tableView.dequeueReusableCell( withIdentifier: "MyCell", for: indexPath ) as MyTableViewCell // 'UITableViewCell' is not convertible to 'MyTableViewCell'; did you mean to use 'as!' to force downcast? 我们的错误是,UITableViewCel
let cell = tableView.dequeueReusableCell(
withIdentifier: "MyCell",
for: indexPath
) as MyTableViewCell // 'UITableViewCell' is not convertible to 'MyTableViewCell'; did you mean to use 'as!' to force downcast?
我们的错误是,UITableViewCell
无法转换为MyTableViewCell
因此,编译器建议进行强制转换:
let cell = tableView.dequeueReusableCell(
withIdentifier: "MyCell",
for: indexPath
) as! MyTableViewCell // ?!?!?!
然而,这感觉很难看
在处理tableView(tableView:UITableView,cellForRowAt indexPath:indexPath)时,除了强制强制强制转换之外,没有其他选择吗
?这真的是用Swift实现这一点最惯用的方法吗
谢谢
这真的是最惯用的方式吗
当然。这是完全标准的
您可以像这样安全地俯冲:
if let cell = tableView.dequeueReusableCell(
withIdentifier: "MyCell",
for: indexPath
) as? MyTableViewCell {
guard let cell = tableView.dequeueReusableCell(
withIdentifier: "MyCell",
for: indexPath
) as? MyTableViewCell else {
// Log an error, or fatalError("Wrong cell type."), etc.
// or maybe return UITableViewCell()
}
但这是一种我认为不值得这么做的情况,因为如果这不是MyTableViewCell,那么你真的想崩溃。你可以这样做:
if let cell = tableView.dequeueReusableCell(
withIdentifier: "MyCell",
for: indexPath
) as? MyTableViewCell {
guard let cell = tableView.dequeueReusableCell(
withIdentifier: "MyCell",
for: indexPath
) as? MyTableViewCell else {
// Log an error, or fatalError("Wrong cell type."), etc.
// or maybe return UITableViewCell()
}
类型系统不能在一开始就消除任何类型转换的需要吗?我想到了相关的类型和泛型。事实上,我相信在某些情况下你可能不想崩溃。例如,如果单元重用失败或类似的情况,那么强制向下转换将失败,它实际上应该返回一个新单元。我总是这样做:
let cell=tableView.dequeueReusableCell(标识符为:“MyCell”,for:indexath)as?MyTableViewCell??MyTableViewCell()。根据定义,它永远不会失败。非可选值不能崩溃。@FedericoOjeda较旧的可重用单元(带标识符:)
(不带索引路径)可以返回nil
。无法使用indexPath
的。您在Interface Builder中设计了MyTableViewCell
。你应该记住这一点。如果应用程序在这一行中崩溃,这是一个永远不会在运行时发生的设计错误。这与将IBOutlets定义为vars with!没有太大区别!。