Swift中的多类型约束

假设我有这些协议:
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 clause,它允许您指定任意数量的需求(所有必须满足),用逗号分隔

Swift 2:

func someFunc<T where T:SomeProtocol,T:SomeOtherProtocol>(arg: T) {
    // stuff
}

Swift 3:

func someFunc<T: SomeProtocol & SomeOtherProtocol>(arg: T) {
    // stuff
}

或者更强大的where子句:

func someFunc<T>(arg: T) where T:SomeProtocol,T:SomeOtherProtocol{
    // stuff
}

您当然可以使用协议组合(例如,协议< SomeProtocol,SomeOtherProtocol>),但它有点不太灵活。

使用在哪里让你处理涉及多种类型的情况。

您可能仍然希望组合协议在多个地方重用,或者只是为了使编写的协议具有有意义的名称

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...