gpt4 book ai didi

arrays - Swift 4 无法使用类型的参数列表调用 'index'

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:38 24 4
gpt4 key购买 nike

我在调用数组方法 index(of:) 时遇到问题。MyClass 继承自UIViewController,符合MyDelegate协议(protocol)。

//self.viewControllers: [(UIViewController & MyDelegate)]
guard let myController = viewController as? MyClass,
let index = self.viewControllers.index(of: myController) else {return}

然后我得到错误:

Cannot invoke 'index' with an argument list of type '(of: (UIViewController & MyDelegate))'

我该如何解决这个问题,有没有比在扩展中实现 index(of:) 更好的解决方案?

extension Array where Element == (UIViewController & MyDelegate) { 
func index(of: Element) -> Int? {
for i in 0..<self.count {
if self[i] == of {
return i
}
}
return nil
}
}

最佳答案

这几乎可以肯定只是协议(protocol)(又名存在性)don't conform to themselves 事实的延伸。 .所以 class existential UIViewController & MyDelegate不符合 Equatable , 即使 UIViewController

因此因为index(of:)仅限于在 Collection 上被调用与 Equatable元素,你不能在 [UIViewController & MyDelegate] 上调用它.

这是一个更简单的例子:

protocol P {}
protocol X {}
class Foo : P {}

func foo<T : P>(_ t: T) {}

func bar(_ f: Foo & X) {
// error: Protocol type 'Foo & X' cannot conform to 'P' because only concrete
// types can conform to protocols
foo(f)
}

我们不能通过 f作为 foo(_:) 的参数作为Foo & X不符合 P , 即使 Foo做。然而,实际上这应该是一个明确的例子,即存在的应该总是能够符合自身,所以我继续 filed a bug .

在修复之前,一个简单的解决方案就是对具体类型进行中间转换——因此在我们的示例中,我们可以这样做:

foo(f as Foo)

在您的示例中,您可以:

let index = (self.viewControllers as [UIViewController]).index(of: myController) 

关于arrays - Swift 4 无法使用类型的参数列表调用 'index',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44485191/

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