Optional Binding on Implicitly Unwrapped Optional

你说的曾经没有我的故事 提交于 2019-12-06 11:27:40

问题


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?


回答1:


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
}



回答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.



来源:https://stackoverflow.com/questions/24481836/optional-binding-on-implicitly-unwrapped-optional

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