简体   繁体   中英

swift indexOf for [AnyObject] array

Trying to get the index of an array ( [AnyObject] ). What's the part that I'm 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 have tried with Swift 1.2 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
  }

输入'AnyObject?'不符合协议'Equatable' 无法分配“Int?”类型的不可变值

We need to cast the object we're testing to a UIViewController , since we know that are array of controllers is holding UIViewController s (and we know that UIViewController s conform to 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 behind the error is that in order for the indexOf method to compare the object you pass in, it must compare them using the == operator. The Equatable protocol specifies that the class has implemented this function, so this is what indexOf requires its arguments conform to.

Objective-C doesn't have this same requirement, but the actual Objective-C implementation ends up meaning that the argument is compared with objects in the array using the isEqual: method (which NSObject and therefore all Objective-C classes implement).

You have to cast the viewController property to an Array object:

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

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