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 opti
Implicitly unwrapped optionals introduce a possible failure similar to dereferencing null pointers. You should only use them when you can be sure that no one will accidentally pass nil, or when you're comfortable telling clients of the interface that the function will crash if they violate the interface requirements.
Another way to avoid using ? Repeatedly is the if let statement:
func foo(bar:Int?) -> Int? {
if let x = bar {
if Int.max / x >= x {
return x * x
}
}
return nil
}
x
here is an Int
rather than Int?
.
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 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.