swift – 使用或不使用’where’子句与泛型有什么区别?

swift – 使用或不使用’where’子句与泛型有什么区别?,第1张

概述这两种声明带有或不带’where’子句泛型超类的方法有什么区别? 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 这两种声明带有或不带’where’子句的泛型超类的方法有什么区别?

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.

简单地说,在其中允许您指定关于通用参数的关联类型的约束,而在<>中你不能这样做.

总结

以上是内存溢出为你收集整理的swift – 使用或不使用’where’子句与泛型有什么区别?全部内容,希望文章能够帮你解决swift – 使用或不使用’where’子句与泛型有什么区别?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1005046.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存