swift [AnyObject] 数组的 indexOf

swift indexOf for [AnyObject] array

正在尝试获取数组的索引 ([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?
      }
    }

我试过 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
  }

您必须将 viewController 属性 转换为数组对象:

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

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

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

错误背后的逻辑是,为了让 indexOf 方法比较您传入的对象,它必须使用 == 运算符比较它们。 Equatable 协议指定 class 已经实现了这个功能,所以这就是 indexOf 要求它的参数符合。

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