Skip to content

Instantly share code, notes, and snippets.

@a2
Created July 4, 2017 09:48
Show Gist options
  • Save a2/50e8cb0929bd30768752fc3a0b9a5b72 to your computer and use it in GitHub Desktop.
Save a2/50e8cb0929bd30768752fc3a0b9a5b72 to your computer and use it in GitHub Desktop.
// Version A
// - crashes if viewControllers is empty
// - crashes if first VC is not of type MyViewController
let navigationController = ...
let myViewController = navigationController.viewControllers.first as! MyViewController
myViewController.configurationObject = ...
// Version B
// - doesn't crash, ever
// - does nothing if viewControllers is empty or the first is not of type MyViewController
let navigationController = ...
if let myViewController = navigationController.viewControllers.first as? MyViewController {
myViewController.configurationObject = ...
}
// Version C
// - adds an `else` clause to version B
else {
print("View controllers is empty or the first is not of type \(MyViewController.self)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment