[AnyObject]数组的swift indexOf

时间:2015-08-19 12:19:35

标签: ios arrays 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?
      }
    }

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

Type 'AnyObject?' does not conform to protocol 'Equatable' Cannot assign to immutable value of type 'Int?'

2 个答案:

答案 0 :(得分:5)

我们需要将我们正在测试的对象转换为UIViewController,因为我们知道controllers的数组正在保持UIViewController(我们知道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协议指定该类已实现此函数,因此indexOf要求其参数符合。

Objective-C没有相同的要求,但实际的Objective-C实现最终意味着使用isEqual:方法(NSObject $array2['someOtheField'] = isset($array1['somefield'])?$array1['somefield']:null; 方法将参数与数组中的对象进行比较因此所有Objective-C类都实现了。

答案 1 :(得分:0)

您必须将viewController属性强制转换为Array对象:

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