在Swift中与as和as一起下降? [英] Downcasting in Swift with as and as?

查看:182
本文介绍了在Swift中与as和as一起下降?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the difference between these two code snippets:

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

结果不是完全一样吗?

推荐答案

在这段代码中没有区别,在这两种情况下,它的计算结果为 UITableViewCell?

In that code there's no difference, in both cases it evaluates to UITableViewCell?

真正的区别是:


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

  • in the first case a downcast to UITableViewCell? is expected to always succeed (even if it's nil), so if dequeueReusableCellWithIdentifier returns something that's not an instance of UITableViewCell (or an instance of a class inherited from it), it fails at runtime. The expression returns an optional UITableViewCell?

dequeueReusableCellWithIdentifier 返回的既不是 UITableViewCell 的实例也不是子类的实例,因此下降优雅地评估为nil没有运行时错误)。

in the second case the cast is optional: if the object returned by dequeueReusableCellWithIdentifier is neither an instance of UITableViewCell nor an instance of a subclass, the downcast gracefully evaluates to nil (hence with no runtime error).

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

Of course dequeueReusableCellWithIdentifier always returns a UITableViewCell, that's why there's no difference in your code. But in other contexts the difference may exist and you have to take care of that to prevent runtime errors

这篇关于在Swift中与as和as一起下降?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆