【发布时间】:2014-06-06 19:17:18
【问题描述】:
假设我有这些协议:
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>
【问题讨论】:
-
这是一个特别相关的问题,因为 Swift 文档在泛型章节中没有提到这一点......
标签: swift