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?
- NSTableView with custom cells
- Xcode ARC (automatic reference counting), “release is unavailable”
- Adding View controllers as subview in Swift
- Executing shell commands with NSTask - Objective-C Cocoa
- OS X app update issue with Sparkle under Mavericks and XCode 5
- Cocoa/ Objective-C Shell Command Line Execution
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
- MKMapView doesn't zoom correctly while user tracking mode is MKUserTrackingModeFollowWithHeading
- UIAlertController text alignment
- Files disappearing from NSLibraryDirectory
- NSUbiquityIdentityDidChangeNotification doesn't work?
- JSON structure with Swift and Alamofire
- FBSDKAccessToken currentAccessToken nil after quitting app
- Changing the name of the committer in Xcode
- Linker error when accessing application module in UI tests in XCode 7.1
- How to “Show my current location on google maps, when I open the ViewController?” in Swift?
- How to change the background color of the UIAlertController?
- Fonts on launch screen are different than main storyboard
- Why is the extension of my Swift class not visible outside the defining file?
- Why is Xcode's Variables View's “Edit Value” not changing the variable value?
- How to Programmatically check and open an existing app in iOS 8?
- The operation couldn’t be completed. (Cocoa error 260.)