在斯威夫特Down与as?

时间:2014-09-26 10:18:39

标签: cocoa swift downcast

这两个代码段之间有什么区别:

let cell = tableView.dequeueReusableCellWithIdentifier("cellId") as UITableViewCell?
// vs
let cell = tableView.dequeueReusableCellWithIdentifier("cellId") as? UITableViewCell

结果不完全相同吗?

3 个答案:

答案 0 :(得分:14)

在该代码中没有区别,在这两种情况下它都评估为UITableViewCell?

真正的区别在于:

  • 在第一种情况下,预期UITableViewCell?的向下投射总是成功(即使它是零),所以如果dequeueReusableCellWithIdentifier返回的内容不是UITableViewCell的实例(或从其继承的类的实例),它在运行时失败。表达式返回一个可选的UITableViewCell?

  • 在第二种情况下,强制转换是可选的:如果dequeueReusableCellWithIdentifier返回的对象既不是UITableViewCell的实例也不是子类的实例,则downcast优雅地计算为nil(因此没有运行时错误)。

当然dequeueReusableCellWithIdentifier总是会返回UITableViewCell,这就是为什么代码没有区别的原因。但在其他情况下,可能存在差异,您必须注意这一点以防止运行时错误

答案 1 :(得分:6)

asas?之间的主要区别在于as是强制转换的,如果不成功则会崩溃。如果转换成功,as?将返回包含值的可选值,如果不成功,则返回nil

答案 2 :(得分:1)

asas?

之间的区别
  • as? UITableViewCell表示当您不知道自己是downcasting时,您假设为UITableViewCell,但可能是IntegerFloatArrayDictionary

  • as UITableViewCell?表示它是Optional Value,可能包含UITableViewCellNil值。