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?
The difference between,
as
andas?
as? UITableViewCell
means when you don't know what you'redowncasting
, you are assuming that as aUITableViewCell
, but it might meInteger
orFloat
orArray
orDictionary
.as UITableViewCell?
means it's anOptional Value
, it may either contain aUITableViewCell
orNil
value.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 ifdequeueReusableCellWithIdentifier
returns something that's not an instance ofUITableViewCell
(or an instance of a class inherited from it), it fails at runtime. The expression returns an optionalUITableViewCell?
in the second case the cast is optional: if the object returned by
dequeueReusableCellWithIdentifier
is neither an instance ofUITableViewCell
nor an instance of a subclass, the downcast gracefully evaluates to nil (hence with no runtime error).Of course
dequeueReusableCellWithIdentifier
always returns aUITableViewCell
, 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 errorsMain difference between
as
andas?
is thatas
is forced cast and will crash if unsuccessful.as?
will return optional value containing value if cast was successful andnil
if unsuccessful.