简体   繁体   中英

Swift protocol multiple matching functions named error

I have a protocol and class like below,

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" .

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? The test that returns [[T]] or the test that returns [T] ? It could call both, couldn't it? It could call the first test because T could be inferred as [Int] . It could call the second test because T could be inferred as 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.

If you remove the second test , BaseTest will conform to the protocol:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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