Swift 中的多种类型约束 [英] Multiple Type Constraints in Swift

查看:59
本文介绍了Swift 中的多种类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这些协议:

protocol SomeProtocol {

}

protocol SomeOtherProtocol {

}

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

Now, if I want a function that takes a generic type, but that type must conform to SomeProtocol I could do:

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

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

But is there a way to add a type constraint for multiple protocols?

func bothFunc<T: SomeProtocol | SomeOtherProtocol>(arg: T) {

}

类似的事情使用逗号,但在这种情况下,它将开始不同类型的声明.这是我尝试过的.

Similar things use commas, but in this case, it would start the declaration of a different type. Here's what I've tried.

<T: SomeProtocol | SomeOtherProtocol>
<T: SomeProtocol , SomeOtherProtocol>
<T: SomeProtocol : SomeOtherProtocol>

推荐答案

您可以使用 where 子句 允许您根据需要指定尽可能多的要求(所有这些都必须满足)分隔逗号

You can use a where clause which lets you specify as many requirements as you want (all of which must be fulfilled) separated by commas

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

斯威夫特 3 &4:

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

或更强大的 where 子句:

or the more powerful where clause:

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

您当然可以使用协议组合(例如, protocol ),但它不太灵活.

You can of course use protocol composition (e.g., protocol<SomeProtocol, SomeOtherProtocol> ), but it's a little less flexible.

使用 where 可以处理涉及多种类型的情况.

Using where lets you deal with cases where multiple types are involved.

您可能仍想组合协议以在多个地方重用,或者只是为组合协议指定一个有意义的名称.

You may still want to compose protocols for reuse in multiple places, or just to give the composed protocol a meaningful name.

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

这感觉更自然,因为协议在参数旁边.

This feels more natural as the protocols are next to the argument.

这篇关于Swift 中的多种类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆