假设我有以下协议:
protocol SomeProtocol {
}
protocol SomeOtherProtocol {
}
现在,如果我想要一个采用通用类型的函数,但是该类型必须符合SomeProtocol
我的要求,则可以执行以下操作:
func someFunc<T: SomeProtocol>(arg: T) {
// do stuff
}
但是,有没有一种方法可以为多个协议添加类型约束?
func bothFunc<T: SomeProtocol | SomeOtherProtocol>(arg: T) {
}
类似的事情使用逗号,但是在这种情况下,它将开始不同类型的声明。这是我尝试过的。
<T: SomeProtocol | SomeOtherProtocol>
<T: SomeProtocol , SomeOtherProtocol>
<T: SomeProtocol : SomeOtherProtocol>
您可以使用where子句,该子句允许您指定任意数量的要求(必须满足所有要求),并用逗号分隔
func someFunc<T where T:SomeProtocol, T:SomeOtherProtocol>(arg: T) {
// stuff
}
func someFunc<T: SomeProtocol & SomeOtherProtocol>(arg: T) {
// stuff
}
或更强大的where子句:
func someFunc<T>(arg: T) where T:SomeProtocol, T:SomeOtherProtocol{
// stuff
}
您当然可以使用协议组合(例如protocol<SomeProtocol, SomeOtherProtocol>
),但灵活性稍差一些。
使用where
可以处理涉及多种类型的情况。
您可能仍然想编写协议以便在多个地方重用,或者只是给组成的协议起一个有意义的名字。
func someFunc(arg: SomeProtocol & SomeOtherProtocol) {
// stuff
}
由于协议离论点很近,因此感觉更自然。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句