使用或不使用'where'子句与泛型之间有什么区别? [英] What's the difference between using or not using the 'where' clause with generics?

查看:136
本文介绍了使用或不使用'where'子句与泛型之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种声明泛型超类有或没有'where'子句的方法有什么区别?

What's the difference between these two methods of declaring a generics superclass with or without the 'where' clause?

func foo<T: SomeClass>(object: T) -> Array<T>

func foo<T>(object: T) -> Array<T> where T: SomeClass


推荐答案

a href =https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/GenericParametersAndArguments.html =nofollow noreferrer> Swift指南:

This is clearly stated in the Swift guide:


泛型where子句中的要求指定类型
参数从类继承,或者符合协议或协议
组合。虽然泛型where子句提供了语法
sugar来表示对类型参数的简单约束(对于
实例,< T:Comparable> 等价于< T>其中T:Comparable
等等),您可以使用它来为类型
参数及其关联类型提供更复杂的约束。例如,你可以限制
类型参数的相关类型以符合协议。对于
的例子,< S:Sequence>其中S.Iterator.Element:Equatable 指定
S 符合序列协议,并且相关联的类型
S.Iterator.Element 符合 Equatable 协议。这个约束
确保序列中的每个元素都是可以等值的。

The requirements in a generic where clause specify that a type parameter inherits from a class or conforms to a protocol or protocol composition. Although the generic where clause provides syntactic sugar for expressing simple constraints on type parameters (for instance, <T: Comparable> is equivalent to <T> where T: Comparable and so on), you can use it to provide more complex constraints on type parameters and their associated types. For instance, you can constrain the associated types of type parameters to conform to protocols. For example, <S: Sequence> where S.Iterator.Element: Equatable specifies that S conforms to the Sequence protocol and that the associated type S.Iterator.Element conforms to the Equatable protocol. This constraint ensures that each element of the sequence is equatable.

简单地说, where 可以指定关于通用参数的关联类型的约束,而在<> 中,您不能这样做。

Simply put, where lets you specify constraints about the associated types of a generic parameter, while in <> you can't do this.

这篇关于使用或不使用'where'子句与泛型之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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