[英]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
}
我们需要将我们正在测试的对象转换为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类实现)将参数与数组中的对象进行比较。
您必须将viewController属性强制转换为Array对象:
if let controllers = self.viewControllers as? [UIViewController] {
self.nextIndex = controllers.indexOf(controller)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.