Swift Programming Guide says "You can also use an implicitly unwrapped optional with optional binding, to check and unwrap its value in a single statement". Why do you need to use optional binding when the value is already unwrapped? Does option binding unwrap it again?
Asked
Active
Viewed 340 times
2 Answers
2
Calling an implicitly unwrapped is the same as calling a regular optional with ! after it. It can still hold a nil value and calling it when it's nil will result in a runtime error, so you use the if let optional binding if you aren't sure if it is nil or not.
var myOptional: Int! = nil
10 + myOptional //runtime error
if let myUnwrapped = myOptional{
10 + myOptional //safe
}

Connor Pearson
- 63,902
- 28
- 145
- 142
-
Just calling the optional like the second line of code automatically unwraps the optional nil or not. The if let checks, then unwraps. – Connor Pearson Jun 30 '14 at 01:36
-
So optional binding essential unwraps it once more? In this case could you skip if let myUnwrapped and just check if myOptional since you are not using myUnwrapped? – Boon Jun 30 '14 at 02:11
-
It's just a more safe way of unwrapping – Connor Pearson Jun 30 '14 at 02:12
-
@Boon you can also do `if let _ = myOptional { ... }` since you don't plan to use myUnwrapped – FernandoEscher Aug 19 '15 at 16:00
2
Why do you need to use optional a binding when the value is already unwrapped
It is not already unwrapped. An implicitly unwrapped optional is just an optional. It implicitly unwraps when used in certain expressions (postfix expressions, the same expressions where optional binding has an effect). But otherwise, it's just an optional, not unwrapped. You can use optional binding with it like with other optionals.

newacct
- 119,665
- 29
- 163
- 224