Skip to content

Instantly share code, notes, and snippets.

@apbendi
Last active April 15, 2016 16:50
Show Gist options
  • Save apbendi/a055214778381283205318f485086e06 to your computer and use it in GitHub Desktop.
Save apbendi/a055214778381283205318f485086e06 to your computer and use it in GitHub Desktop.
// Find the first ViewController of an arbitrary type anywhere in the hierarchy of a base ViewController
private func findParent<V: UIViewController>(ofViewController viewController: UIViewController?) -> V? {
if let typedViewController = viewController as? V {
return typedViewController
}
guard let parentViewController = viewController?.parentViewController else {
return nil
}
return findParent(ofViewController: parentViewController)
}
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// These two calls will return different things, because the type V is inferred by
// the annotation on the left hand side of the assignment
let navController: UINavigationController? = findParent(ofViewController: self)
let tabController: UITabBarController? = findParent(ofViewController: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment