加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:25:32 所属栏目:百科 来源:网络整理
导读:我有一个调用数组方法索引(:)的问题. MyClass继承自UIViewController并符合MyDelegate协议. //self.viewControllers: [(UIViewController MyDelegate)]guard let myController = viewController as? MyClass,let index = self.viewControllers.index(of: myC
我有一个调用数组方法索引(:)的问题.
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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读