如何创建Swift Generic variadic函数



这是我的代码

protocol P {}
class BaseClass {}
class AA: BaseClass, P {}
class BB: BaseClass {}
class CC: BaseClass, P {}

func test1<T>(value: T.Type...) where T: BaseClass & P {
}

在这里,我们有2个子类AABB的子类。

AACC conforms to consote PBB 符合协议P

我如何使用该函数仅接受多个参数AACC,但拒绝BB

我尝试了以下方法:

test(AA.self, BB.self)

这给了我编译时间错误。有什么办法可以实现上述行为?

一种方法可能是声明BaseClassP配对的typealias

protocol P {}
class BaseClass {}
class AA: BaseClass, P {}
class BB: BaseClass {}
class CC: BaseClass, P {}
typealias BaseP = BaseClass & P
func test1(value: BaseP.Type...) {
    for t in value {
        print(t)
    }
}
test1(value: AA.self, CC.self) // prints "AA" and "CC"
// fails: "cannot convert value of type 'BB.Type' to expected argument type 'BaseP.Type' (aka '(BaseClass & P).Type')"
//test1(value: AA.self, BB.self) 

最新更新