2015-11-08 88 views
1

我对Swift非常陌生,正在试图将UITableViewCell强制转换为我设置的协议或基本单元类,然后使用它的方法。对我来说,我无法让编译器沉默它的警告,我不知道如何解决这个问题。下面是我采取了不同的方法:在Swift中铸造问题

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中获得正确的语法。我会很感激任何帮助!

+0

请出示BaseCell和CellDimensions – Kametrixom

+1

的声明第二种格式是正确的。我建议你设置一个断点并进入代码,以确定何处/为什么得到运行时异常。是的,请显示单元类和'computeHeight'方法的声明。 – Paulw11

+0

您声明'BaseCell'遵循CellDimension协议。 BaseCell应该是 'class BaseCell:UICollectionViewCell {}' 正如Paul所说,你在表格视图中的第二个代码是正确的。 – Tim

回答

0

你的第二个是垂头丧气的正确方法:

if let cell = tableView.cellForRowAtIndexPath(indexPath) as? BaseCell { 
    return cell.computeHeight() 
} 

在这第二个,if语句中的cell编译时类型BaseCell

第一个(if cell is BaseCell)是BaseCell类型的有效检查 - 有条件的作品 - 但实际上并没有改变cell变量的类型。正如编译器错误所述,它的编译时类型仍然是UITableViewCell

第三个只是第一个错综复杂的变体。

为什么在第二个EXC_BAD_ACCESS?没有看到代码的其余部分很难说,但它不是你的演员。有两种可能的可能性:(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)")