如何创建快速通用的可变参数函数?

FlowUI。SimpleUITesting.com

这是我的代码

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个BaseClassAA和的子类BB

AACC 符合协议PBB 符合协议P

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

我已经试过了:

test(AA.self, BB.self)

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

提姆

一种方式是申报typealias的配对BaseClassP

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) 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章