Swift中[AnyObject]数组的indexOf方法

4

我想要获取数组([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
也许可以尝试另一种方式,将self.viewControllers强制转换为[UIViewController]类型? - Aderstedt
@Aderstedt:我得到了这个错误信息:“无法使用类型为‘(AnyObject?)’的参数列表调用‘indexOf’”。你有什么想法吗? - el.severo
就像往常一样,错误信息中的“问号”很重要。 - Martin R
2个回答

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和因此所有Objective-C类都实现)与数组中的对象进行比较。

0

你需要将viewController属性转换为数组对象:

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

@nhgrif 为什么会很昂贵? - Tim Specht
抱歉...如果self.viewControllers没有被声明为[UIViewController](从问题中无法确定),那么这部分可能是必要的。但是你错过了我们需要将controller转换为UIViewController的部分,正如我的答案所描述的那样。 - nhgrif
实际上,仔细阅读问题后,将数组本身转换是完全不必要的。看看正在使用的“indexOf”实现即可。 - nhgrif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接