加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift中的多类型约束

发布时间:2020-12-14 06:13:13 所属栏目:百科 来源:网络整理
导读:假设我有这些协议: protocol SomeProtocol {}protocol SomeOtherProtocol {} 现在,如果我想要一个函数采用通用类型,但该类型必须符合SomeProtocol我可以做: func someFuncT: SomeProtocol(arg: T) { // do stuff} 但是有没有办法添加一个类型约束多个协
假设我有这些协议:
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>),但它有点不太灵活。

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读