I believe I understand why optionals are handy (my best thought for use is to be able to return a nil Boolean value), but in what case would I want to declare a wrapped optional using ? rather than ! for an implicitly unwrapped optional.
It just seems unnecessary to declare it with ? and then have to type ! all over the place rather than just using ! once.
I don't want to disregard the ? as useless, but I just can't find a use for it... Any ideas?
Checking an optionals value is called “unwrapping”, because we're looking inside the optional box to see what it contains. Implicitly unwrapping that optional means that it's still optional and might be nil, but Swift eliminates the need for unwrapping.
Implicitly unwrapped optionals are useful when an optional's value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter.
The outlet is declared as an implicitly unwrapped optional, not an optional. Remember that the @IBOutlet Interface Builder attribute indicates the property is an outlet.
Unwrap an optional type with the nil coalescing operator If a nil value is found when an optional value is unwrapped, an additional default value is supplied which will be used instead. You can also write default values in terms of objects.
If you try to access the content of an implicitly unwrapped optional and there's nothing there, your app will crash.
If you use the patterns for checking the content of an optional — like optional binding and optional chaining - you can control how your app should fail gracefully in unforeseen situations. And it doesn't make your code all that more complicated.
Not crashing seems like a good reason to me.
First lets talk about what the point of ? is in swift. You might create a var that looks like this.
var number : Int?
You are basically saying that there is a possibility that this variable could be nil. If there is ever a possibility that an object could be nil, then you would not want to do something like this.
var secondNumber = number! + 5
Basically in that statement you are saying, there is a possibility this variable could be nil but, I will totally ignore that fact and pretend there is no way that it could be nil.
Instead you will want to check if that variable exists first and then set it like so
var number : Int?
var number2 : Int?
number = 10
if let unwrappedNumber = number {
number2 = unwrappedNumber + 5
}
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With