Your AnyObject problem. (If in doubt, your problem is always AnyObject , it is an evil type that should be avoided as much as possible. The only thing worse: AnyObject? )
tabBarController.viewControllers problem that tabBarController.viewControllers returns [AnyObject]? , and optional advertising probably makes things move sideways. He probably promotes AnyObject? before AnyObject?? and then confused. This is more of a compiler error, but just the madness that comes with AnyObject . Therefore, the answer is to get rid of it as quickly as you can.
Instead of this:
for subcontroller in tabBarController.viewControllers! {
Do you want to:
if let viewControllers = tabBarController.viewControllers as? [UIViewController] { for subcontroller in viewControllers {
So the full code:
if let tabBarController = topViewController as? UITabBarController { if let viewControllers = tabBarController.viewControllers as? [UIViewController] { for subcontroller in viewControllers { if let subcontrollerView = subcontroller.view { if subcontrollerView.window != nil && subcontroller.isViewLoaded() { topViewController = subcontroller break; } } } } }
But we can do better. First, an optional chain is often the best way to manage multiple if-lets, and when that doesn't work, we can use the new Swift 1.2 syntax with multiple syntaxes to get this:
if let tabBarController = topViewController as? UITabBarController, viewControllers = tabBarController.viewControllers as? [UIViewController] { for subcontroller in viewControllers { if subcontroller.view?.window != nil && subcontroller.isViewLoaded() { topViewController = subcontroller break; } } }
source share