Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

cocoa - Downcasting in Swift with as and 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

Isn't the result exactly the same?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...