[AnyObject]数组的swift indexOf

el.*_*ero 4 arrays ios swift equatable

试图获取数组的索引([AnyObject]).我错过了什么部分?

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?
      }
    }
Run Code Online (Sandbox Code Playgroud)

我尝试过使用Swift 1.2这种方法:

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
  }
Run Code Online (Sandbox Code Playgroud)

输入'AnyObject?'  不符合协议'Equatable' 无法分配

nhg*_*rif 5

我们需要将我们正在测试的对象强制转换为a UIViewController,因为我们知道controllers正在持有UIViewControllers的数组(并且我们知道UIViewControllers符合Equatable.

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

错误背后的逻辑是,为了使indexOf方法比较传入的对象,它必须使用==运算符对它们进行比较.该Equatable协议指定该类已实现此函数,因此这indexOf需要其参数符合.

Objective-C没有相同的要求,但实际的Objective-C实现最终意味着使用该isEqual:方法将参数与数组中的对象进行比较(NSObject因此所有Objective-C类都实现).