大佬教程收集整理的这篇文章主要介绍了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>
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>),但它有点不太灵活。
使用在哪里让你处理涉及多种类型的情况。
您可能仍然希望组合协议在多个地方重用,或者只是为了使编写的协议具有有意义的名称。
以上是大佬教程为你收集整理的Swift中的多类型约束全部内容,希望文章能够帮你解决Swift中的多类型约束所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。