Last active
April 15, 2016 16:50
-
-
Save apbendi/a055214778381283205318f485086e06 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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