swift - 使用或不使用泛型的 'where' 子句有什么区别?

标签 swift generics

这两种使用或不使用“where”子句声明泛型父类(super class)的方法有什么区别?

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

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

最佳答案

这在 Swift guide 中有明确说明:

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允许您指定有关泛型参数关联类型的约束,而在 <> 中你不能这样做。

关于swift - 使用或不使用泛型的 'where' 子句有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46810009/

相关文章:

ios - 无法转换 NSURL 类型的值? _ 类型的预期参数?

java - 将具有类型参数的类传递/返回给函数

ios - Xcode 上的 Swift._ArrayBuffer._copyContents

ios - 从注释中单击按钮发送对象 swift 4

ios - AdMob 给出 fatal error (展开可选时发现 nil)

generics - Monodroid 泛型不是协变的?

java - 使用对象实例化集合

ios - 线程 1 : EXC_BAD_INSTRUCTION Issue with dismissing keyboard and nil values (. 为 NaN)

swift - GCD全局队列控制

c# - 有没有办法定义两个元素字符串数组的 List<>?