Given the following in Swift:
var optionalString: String?
let dict = NSDictionary()
What is the practical difference between the following two statements:
optionalString = dict.objectForKey("SomeKey") as? String
vs
optionalString = dict.objectForKey("SomeKey") as! String?
as? Types
- means the down casting process is optional. The process can be successful or not(system will return nil if down casting fails).Any way will not crash if down casting fails.as! Type?
- Here the process of down casting should be successful (!
indicates that) . The ending question mark indicates whether final result can be nil or not.More info regarding "!" and "?"
Let us take 2 cases
Consider:
Here we don't know whether the result of down casting of cell with identifier "Cell" to UITableViewCell is success or not. If unsuccessful then it returns nil( so we avoid crash here). Here we can do as given below.
So let us remember it like this - If
?
it means we are not sure whether value is nil or not (question mark comes when we don't know things).Contrast that to:
Here we tell the compiler that down casting should be successful. If it fails the system will crash. So we give
!
when we are sure that value is non nil.The practical difference is this:
optionalString
will be a variable of typeString?
. If the underlying type is something other than aString
this will harmlessly just assignnil
to the optional.This says, I know this thing is a
String?
. This too will result inoptionalString
being of typeString?
, but it will crash if the underlying type is something else.The first style is then used with
if let
to safely unwrap the optional:Maybe this code example will help someone grok the principle:
as
used for upcasting and type casting to bridged typeas?
used for safe casting, return nil if failedas!
used to force casting, crash if failedNote:
as!
can’t cast raw type to optionalExamples:
Example
By adding a ? immediately after the data type you tell the compiler that the variable might contain a number or not. Neat! Notice that it doesn’t really make sense to define Optional constants – you can set their value only once and therefore you would be able to say whether their value will be nil or not.
When we should use "?" and when "!"
let’s say we have UIKit based simple app. we have some code in our view controller and wants to present a new view controller on top of it. and we need to decide to push the new view on screen using navigation controller.
As we know every ViewController instance has a property navigation controller. If you are building a navigation controller based app this property of your app’s master view controller is set automatically and you can use it to push or pop view controllers. If you use a single app project template – there won’t be a navigation controller created automatically for you, so your app’s default view controller will not have anything stored in the navigationController property.
I’m sure you already guessed that this is exactly a case for an Optional datatype. If you check UIViewController you will see that the property is defined as:
So let’s go back to our use case. If you know for a fact that your view controller will always have a navigation controller you can go ahead and force unwrap it:
When you put a ! behind the property name you tell the compiler I don’t care that this property is optional, I know that when this code executes there always will be a value store so treat this Optional like a normal datatype. Well isn’t that nice? What would happen though if there isn’t a navigation controller to your view controller? If you suggestion that there always will be a value stored in navigationController was wrong? Your app will crash. Simple and ugly as that.
How about if you aren’t sure that there always will be a navigation controller? Then you can use ? instead of a !:
What the ? behind the property name tells the compiler is I don’t know whether this property contains nil or a value, so: if it has value use it, and oterwise just consider the whole expression nil. Effectively the ? allows you to use that property just in the case there is a navigation controller. No if checks of any kind or castings of any sort. This syntax is perfect when you don’t care whether you have a navigation controller or not, and want to do something only if there is.
Huge thanks to Fantageek
The first is a "conditional cast" (look under "type-casting operators" in the documentation I've linked). If the cast succeeds, the value of the expression is wrapped in an optional and returned, otherwise the value returned is nil.
The second means that optionalString could be a string object or it might be nil.
More information found in this related question.
It may be easiest to remember the pattern for these operators in Swift as:
!
implies "this might trap," while?
indicates "this might be nil."refer to: https://developer.apple.com/swift/blog/?id=23