gpt4 book ai didi

ios - [AnyObject] 数组的 swift indexOf

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:26 26 4
gpt4 key购买 nike

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

最佳答案

我们需要将我们正在测试的对象转换为 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 协议(protocol)指定该类已经实现了这个函数,所以这就是 indexOf 要求其参数符合的。

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

关于ios - [AnyObject] 数组的 swift indexOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32095349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com