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

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

概述我有一个调用数组方法索引(:)的问题. MyClass继承自UIViewController并符合MyDelegate协议. //self.viewControllers: [(UIViewController & MyDelegate)]guard let myController = viewController as? MyClass,let index = self.viewContr 我有一个调用数组方法索引(:)的问题.
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)
总结

以上是内存溢出为你收集整理的arrays – Swift 4无法使用类型的参数列表调用’index’全部内容,希望文章能够帮你解决arrays – Swift 4无法使用类型的参数列表调用’index’所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1031199.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-23
下一篇2022-05-23

发表评论

登录后才能评论

评论列表(0条)

    保存