Boon
Boon

Reputation: 41480

Optional Binding on Implicitly Unwrapped Optional

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?

Upvotes: 2

Views: 362

Answers (2)

newacct
newacct

Reputation: 122439

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.

Upvotes: 2

Connor
Connor

Reputation: 64644

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
}

Upvotes: 2

Related Questions