加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:36:15 所属栏目:百科 来源:网络整理
导读:这两种声明带有或不带’where’子句的泛型超类的方法有什么区别? func fooT: SomeClass(object: T) - ArrayTfunc fooT(object: T) - ArrayT where T: SomeClass 解决方法 这在 Swift guide中有明确说明: The requirements in a generic where clause speci
这两种声明带有或不带’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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读