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?
3 Solutions Collect From Internet About “Downcasting in Swift with as and as?”
In that code there’s no difference, in both cases it evaluates to
The real difference is:
in the first case a downcast to
UITableViewCell?is expected to always succeed (even if it’s nil), so if
dequeueReusableCellWithIdentifierreturns 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
in the second case the cast is optional: if the object returned by
dequeueReusableCellWithIdentifieris neither an instance of
UITableViewCellnor an instance of a subclass, the downcast gracefully evaluates to nil (hence with no runtime error).
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? 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? UITableViewCellmeans when you don’t know what you’re
downcasting, you are assuming that as a
UITableViewCell, but it might me
as UITableViewCell?means it’s an
Optional Value, it may either contain a
- OpenURL in iOS10
- Extracting Amplitude Data from Linear PCM on the iPhone
- prevent UIAlertView from dismissing
- Swift 3 ObjC Optional Protocol Method Not Called in Subclass
- Difference between framework and static library in xcode4, and how to call them
- How to get data out of bluetooth characteristic in Swift
- How to get detailed language of device in swift
- NSFetchedResultsController: delete 1 row crashes the app
- How to remove CocoaPods from a project?
- How to delete a row from UITableView
- Why are xcodebuild and Xcode 4.2 so slow?
- UIViewControllerTransitioningDelegate method not called in iOS 7
- Xcode cannot find #Include<> header
- Is there a way to check if the iOS device is locked/unlocked?
- Iterating over an array by range