【问题标题】:Swift 4 Cannot invoke 'index' with an argument list of typeSwift 4 无法使用类型的参数列表调用“索引”
【发布时间】:2017-06-11 14:55:43
【问题描述】:

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

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

然后我得到错误:

无法使用类型为“(的:(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 
    } 
}

【问题讨论】:

    标签: arrays swift swift4


    【解决方案1】:

    这几乎可以肯定只是协议(又名存在主义)don't conform to themselves 事实的扩展。所以class existentialUIViewController &amp; MyDelegate 不符合Equatable,尽管UIViewController 符合。

    因此,因为index(of:) 被限制为在带有Equatable 元素的Collection 上调用,所以您不能在[UIViewController &amp; 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 &amp; X 不符合P,即使Foo 符合。然而,实际上这应该是一个明确的例子,即存在的应该总是能够符合自己,所以我继续前进并filed a bug

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

    foo(f as Foo)
    

    在你的例子中,你可以这样做:

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

    【讨论】:

    • 我有一个没有扩展的根类数组,并且在使用index(of:) 时遇到同样的错误。如果我让根类继承自 NSObject,一切正常。关于为什么会这样的任何建议?
    • @jjatie 这听起来像是您的根类不符合Equatable 的情况——通过从NSObject 继承,您获得了一致性(默认情况下基于身份)。你应该做的是让你的类符合Equatable——在这种情况下不需要从NSObject继承。
    • 傻我!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2016-10-09
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多