Optional Binding on Implicitly Unwrapped Optional

时光毁灭记忆、已成空白 提交于 2019-12-04 15:13:11

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
}

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!