简体   繁体   English

Swift协议多个匹配函数命名错误

[英]Swift protocol multiple matching functions named error

I have a protocol and class like below,我有一个协议和 class 如下所示,

protocol Test {
    func test<T>(with string: String) -> Array<T>
    func test<T>(with string: String) -> Array<[T]>
}

class BaseTest {

        func test<T>(with string: String) -> Array<T> {
            return []

        }

        func test<T>(with string: String) -> Array<[T]> {
            return []
        }
    }

It works just fine like that but when I conform the protocol this error appears,它就像那样工作得很好但是当我遵守协议时会出现这个错误,

"1.Multiple matching functions named error" . “1.多个匹配函数命名错误”

I couldn't get it why this is happening.我不明白为什么会这样。

Imagine you have this code:想象一下,您有以下代码:

let protocolVariable: Test = BaseTest()
let array: [[Int]] = protocolVariable.test(with: "")

Which test in BaseTest would the second line call?第二行调用BaseTest中的哪个test The test that returns [[T]] or the test that returns [T] ?返回[[T]]test还是返回[T]test It could call both, couldn't it?它可以同时调用两者,不是吗? It could call the first test because T could be inferred as [Int] .它可以调用第一个test ,因为T可以推断为[Int] It could call the second test because T could be inferred as Int .它可以调用第二个test ,因为T可以被推断为Int

There will still an error if you don't conform to the protocol, but the error will actually be on the call site:如果你不遵守协议,仍然会出现错误,但错误实际上会出现在调用站点上:

let array: [[Int]] = BaseTest().test(with: "") // error

When you conform to a protocol, the compiler will try to match your methods against the ones in the protocol (because it has to check whether your class conforms to the protocol or not), so it will discover this ambiguity earlier.当您遵守协议时,编译器将尝试将您的方法与协议中的方法进行匹配(因为它必须检查您的 class 是否符合协议),因此它会更早地发现这种歧义。

If you remove the second test , BaseTest will conform to the protocol:如果删除第二个testBaseTest将符合协议:

class BaseTest: Test {
    func test<T>(with string: String) -> Array<T> {
        return []

    }
}

But there will still be an error in the first code snippet.但是第一个代码段中仍然会有错误。 if you try to assign it to a [[Int]] , because this time it's ambiguous which of the two protocol methods you mean.如果您尝试将其分配给[[Int]] ,因为这一次您的意思是两种协议方法中的哪一种是模棱两可的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM