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.)
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
.