gpt4 book ai didi

swift - Swift 中的多类型约束

转载 作者:IT王子 更新时间:2023-10-29 04:56:00 27 4
gpt4 key购买 nike

假设我有这些协议(protocol):

protocol SomeProtocol {

}

protocol SomeOtherProtocol {

}

现在,如果我想要一个采用通用类型的函数,但该类型必须符合 SomeProtocol 我可以这样做:

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

但是有没有办法为多个协议(protocol)添加类型约束?

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 和 4:

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

或更强大的 where 子句:

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

您当然可以使用协议(protocol)组合(例如 protocol<SomeProtocol, SomeOtherProtocol> ),但它的灵 active 稍差。

使用 where让您处理涉及多种类型的情况。

您可能仍然希望组合协议(protocol)以在多个地方重用,或者只是为组合的协议(protocol)起一个有意义的名称。

swift 5:

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

这感觉更自然,因为协议(protocol)在参数旁边。

关于swift - Swift 中的多类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24089145/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com