Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了arrays – Swift 4无法使用类型的参数列表调用’index’大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

我有一个调用数组方法索引(:)的问题. MyClass继承自UIViewController并符合MyDelegate协议. //self.viewControllers: [(UIViewController & MyDelegatE)] guard let myController = viewController as? MyClass, let index = self.viewContr
我有一个调用数组方法索引(:)的问题. @H_953_15@myClass继承自UIViewController并符合MyDelegate协议.
//self.viewControllers: [(UIViewController & MyDelegatE)]
guard let myController = viewController as? MyClass,let index = self.viewControllers.index(of: myController) else {return}

然后我得到错误

我怎样才能解决这个问题,是否有比在扩展中实现索引(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’所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。