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

我有一个调用数组方法索引(:)的问题.
MyClass继承自UIViewController并符合MyDelegate协议.
//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))’

我怎样才能解决这个问题,是否有比在扩展中实现索引(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 
    } 
}
这几乎可以肯定只是协议(又称存在) don’t conform to themselves的事实的延伸.所以 class existential UIViewController&即使UIViewController这样做,MyDelegate也不符合Equatable.

因此,因为索引(of :)被限制为在具有Equatable元素的Collection上调用,所以不能在[UIViewController& MyDelegate.

这是一个更小的例子:

protocol P {}
class Foo : P {}

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

let f: (Foo & P) = Foo()
foo(f) // Cannot invoke 'foo' with an argument list of type '((Foo & P))'

我们不能将f作为参数传递给foo(_ :)作为Foo& P不符合P,即使Foo确实如此.然而,这应该是一个明确的案例,表明存在者应该始终能够与自己相符,所以我继续前进,filed a bug.

在修复之前,一个简单的解决方案就是对混凝土类型进行中间转换 – 所以在我们的例子中,我们可以这样做:

foo(f as Foo)

在您的示例中,您可以执行以下操作:

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...