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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With