Swift indexOf for array [AnyObject]

Trying to get the index of an array ( [AnyObject] ). Which part am I missing?

 extension PageViewController : UIPageViewControllerDelegate { func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [AnyObject]) { let controller: AnyObject? = pendingViewControllers.first as AnyObject? self.nextIndex = self.viewControllers.indexOf(controller) as Int? } } 

I tried with Swift 1.2 to use this approach:

 func indexOf<U: Equatable>(object: U) -> Int? { for (idx, objectToCompare) in enumerate(self) { if let to = objectToCompare as? U { if object == to { return idx } } } return nil } 

Type 'AnyObject?' not compliant with protocol Cannot assign immutable value of type 'Int?'

+4
source share
2 answers

We need to pass the object we are testing to the UIViewController , since we know that the array from controllers contains the UIViewController (and we know that the UIViewController matches Equatable .

 extension PageViewController : UIPageViewControllerDelegate { func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [AnyObject]) { if let controller = pendingViewControllers.first as? UIViewController { self.nextIndex = self.viewControllers.indexOf(controller) } } } 

The logic of the error is that in order for the indexOf method indexOf compare the object that you passed, it must compare them using the == operator. The Equatable protocol indicates that the class has implemented this function, therefore it is that indexOf requires matching its arguments.

Objective-C does not have the same requirement, but the actual implementation of Objective-C ends up comparing the argument with the objects in the array using the isEqual: method (which NSObject and therefore all Objective-C implement classes).

+5
source

You need to pass the viewController property to an Array object:

 if let controllers = self.viewControllers as? [UIViewController] { self.nextIndex = controllers.indexOf(controller) } 
0
source

All Articles