Swift协议多个匹配函数,称为错误

问题描述 投票:0回答:1

我有一个类似下面的协议和类,

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 []
        }
    }

它像那样正常工作,但是当我遵循协议时,会出现此错误,

“ 1。多个匹配函数,名称为error”

我无法理解为什么会这样。

swift generics protocols
1个回答
0
投票

您会收到此错误,因为您的第二个函数签名只是第一个函数的专门版本。 T本身可以是Array,因此func test<T>(with string: String) -> Array<T>可以与T == [T]的函数匹配,这意味着您的函数可以与第二个函数的调用匹配。

您可以通过限制通用类型来实现目标,T本身在第二个功能中是Sequence

© www.soinside.com 2019 - 2024. All rights reserved.