![](/img/trans.png)
[英]Trouble casting Error from transaction in SKPaymentTransaction (Swift 3)
[英]Trouble Casting in Swift
我对Swift非常陌生,正在尝试将UITableViewCell强制转换为已设置的协议或基本单元类,然后在其上使用方法。 为了我的一生,我无法让编译器使警告消失,并且我不确定如何解决此问题。 这是我采用的不同方法:
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell is BaseCell {
return cell.computeHeight()
}
}
给出错误: Value of type 'UITableViewCell' has no member 'computerHeight'
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? BaseCell {
return cell.computeHeight()
}
给出EXC_BAD_ACCESS
错误。
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.conformsToProtocol(CellDimensions) {
return cell.computeHeight()
}
}
该错误有2个,第一个是Cannot convert value of type (CellDimension).Protocol (aka 'CellDimension.Protocol') to expected argument type 'Protocol'
,第二个错误与第一个示例的错误相同。
有人知道如何执行此操作吗? BaseCell遵循CellDimension协议,我要获取的单元格应该继承自BaseCell以允许其使用ComputeHeight,但是由于某些原因,我无法在Swift上使用它。 在Objective C上,这是微不足道的,但是我无法在Swift中获得正确的语法。 我将不胜感激!
您的第二个方法是向下转换的正确方法:
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? BaseCell {
return cell.computeHeight()
}
在第二个语句中,在if
语句中, cell
的编译时类型为BaseCell
。
第一个( if cell is BaseCell
)是对BaseCell
类型的有效检查(条件有效),但实际上并未更改cell
变量的类型。 如编译器错误所述,其编译时类型仍为UITableViewCell
。
第三个只是第一个的令人费解的变体。
为什么在第二个中使用EXC_BAD_ACCESS? 如果不看其余的代码就很难说,但这不是您as?
投。
有两种可能的可能性:(1)在cell.computeHeight()
内部崩溃,或者(2)您的as?
转换失败,随后发生的任何代码崩溃。
您可以通过一些调试语句来区分这些可能性:
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? BaseCell {
print("-----> cast succeeded; calling computeHeight()")
return cell.computeHeight()
}
print("-----> cast failed; cell is not BaseCell, but instead is \(cell.dynamicType)")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.