Why use optional binding?

徘徊边缘 提交于 2019-12-10 22:13:21

问题


I am aware that this question is here, but it only partially answers my question and I cannot comment on the answer so I'm forced to post here.

What is the difference between optional binding and just simply using ?. My understanding is when you use ? to unwrap a variable, if it contains a nil value then the code in which it is used isn't run. (Please correct me if this is not the case.)


回答1:


You use optional binding (if let) if you have a block of code that you only want to run if the variable is not nil.

You use optional chaining (the ?) only when accessing the properties/methods of an optional variable.

But there are situations where optional chaining is not possible (i.e. you're not accessing a property/method of the optional variable, but rather using that variable for other purposes). For example

// let's assume `data` is a `NSData?` optional

if let imageData = data {
    let image = UIImage(data: imageData)

    // now do something with `image`
}

We do this because in this context, we can't use optional chaining, and using forced unwrapping (e.g. let image = UIImage(data: data!)) would crash if data was nil.



来源:https://stackoverflow.com/questions/33769366/why-use-optional-binding

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