裁缝强迫施放冲突

时间:2016-05-15 10:13:04

标签: ios swift

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomTableViewCell

它是实现表视图单元格属性的标准句子。但是Tailor(它是一个Swift分析器/ linter)警告你不应该将CustomTableViewCell强制为as!如果我曾经as?,我必须将单元格的属性实现为cell!。但是裁缝并没有警告 [强制型演员]应该避免强制演员。这是什么原因?如何在不打开单元格的情况下实现单元格cell!在Swift中强制转换操作的正确编程范例是什么?

1 个答案:

答案 0 :(得分:1)

我不熟悉"裁缝"但很可能是它给你这个警告的原因是因为如果一个强制转换失败那么显然你的程序会崩溃,而且永远不会好。

如果您100%确定您所投射的是该类型,那么as!运算符确实占有一席之地。但是,即便如此,为了安全而不是抱歉,你应该使用guardif let语句来处理失败的演员。

if let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? CustomTableViewCell {
  //do what you like with cell
}

guard let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? CustomTableViewCell else {
  //abort current scope, return, break, etc. from scope.
}
//do what you like with cast cell