Downcasting in Swift with as and as?

折月煮酒 提交于 2019-11-29 03:32:34

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

The real difference is:

  • 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?

  • 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).

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

Main difference between as and as? is that as is forced cast and will crash if unsuccessful. as? will return optional value containing value if cast was successful and nil if unsuccessful.

The difference between, as and as?

  • as? UITableViewCell means when you don't know what you're downcasting, you are assuming that as a UITableViewCell, but it might me Integer or Float or Array or Dictionary.

  • as UITableViewCell? means it's an Optional Value, it may either contain a UITableViewCell or Nil value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!