简体   繁体   中英

Swift how to find an object in array of AnyObject

I'm trying to get the Index of current ViewController in my NavigationController.

The problem is that navigationController.viewControllers is of type AnyObject, now i get the error Cannot invoke 'find' with an argument list of type (AnyObject, UIViewController).

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    var index = find(navigationController.viewControllers, viewController)
}

How can i fix this, how do i get the Index in an AnyObject array?

This problem occurs because find function doesn't know how to compare AnyObject with UIViewViewController . Even though navigationController.viewControllers 's [AnyObjects] array shouldn't contain anything but UIViewController instances, compiler doesn't know that. We can help it by casting the array (using as! ) to [UIViewController] .

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    var index = find(navigationController.viewControllers as! [UIViewController], viewController)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM