Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the advantage of doing optional binding over sequential binding in Swift?

In the short tutorial here, in step 5 a delegate is assigned:

if let nav = segue.destination as? UINavigationController,
   let classBVC = nav.topViewController as? ClassBVC {
       // 'self' is ClassAVC which has been delegated.
       classBVC.delegate = self
   }

I find it hard to follow this statements, so is it a big disadvantage to just write:

let nav = segue.destination as? UINavigationController
let classBVC = nav?.topViewController as? ClassBVC
classBVC!.delegate = self
like image 844
TMOTTM Avatar asked Dec 02 '25 23:12

TMOTTM


2 Answers

There's no such thing as sequential binding. What you do in the second statement is called optional chaining with optional casting, which would be safe if not for the force unwrapping in your last line.

The force unwrapping here makes your second solution unsafe. If any of the previous optional operations resulted in a nil value, a runtime exception will occur.

classBVC!.delegate = self

If you need to unwrap an optional value, optional binding is one of the best options for doing so. You can make the boilerplate code of optional unwrapping minimal by reducing the number of if let statement. In some scenarios, using guard let instead of if let can also result in clearer code, since you won't have to nest the blocks inside each other.

Using optional binding, you will never see an

unexpectedly found nil while unwrapping an optional value

runtime exception, which you will likely see quite often if you do force unwrapping on optionals which might actually have a nil value.

guard let nav = segue.destination as? UINavigationController, let classBVC = nav.topViewController as? ClassBVC else { return }
classBVC.delegate = self
like image 98
Dávid Pásztor Avatar answered Dec 05 '25 13:12

Dávid Pásztor


Yes, because you are stating that classBVC is absolutely a ClassBVC object. If you wrap it in the if let statement, if one fails it will not crash unwrapping a nil value.

like image 43
Siriss Avatar answered Dec 05 '25 12:12

Siriss



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!