Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use optional binding?

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

like image 872
Josh Avatar asked Dec 19 '25 17:12

Josh


1 Answers

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.

like image 94
Rob Avatar answered Dec 22 '25 10:12

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!