添加未在Swift的标准库中实现的SequenceType

编程入门 行业动态 更新时间:2024-10-27 06:18:30
本文介绍了添加未在Swift的标准库中实现的SequenceType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Swift的标准库中,+运算符仅重载ExtensibleCollectionType和另一种肯定符合SequenceType的类型:

In the standard library of Swift the + operator is only overloaded with ExtensibleCollectionType and another type which definitely conforms to SequenceType:

func + <C : ExtensibleCollectionType, S : CollectionType where S.Generator.Element == C.Generator.Element>(lhs: C, rhs: S) -> C func + <C : ExtensibleCollectionType, S : SequenceType where S.Generator.Element == C.Generator.Element>(lhs: C, rhs: S) -> C func + <C : ExtensibleCollectionType, S : SequenceType where S.Generator.Element == C.Generator.Element>(lhs: S, rhs: C) -> C func + <EC1 : ExtensibleCollectionType, EC2 : ExtensibleCollectionType where EC1.Generator.Element == EC2.Generator.Element>(lhs: EC1, rhs: EC2) -> EC1

那么为什么不同时使用SequenceTypes或至少CollectionTypes重载它们,因为它们可以很容易地添加为Array呢?

So why don't they overload it also with SequenceTypes or at least CollectionTypes since they can easily be added as an Array?:

func + <S1: SequenceType, S2: SequenceType where S1.Generator.Element == S2.Generator.Element>(s1: S1, s2: S2) -> [S1.Generator.Element] { return Array(s1) + Array(s2) }

不实现此重载有任何好处吗?

Are there any benefits don't implementing this overload?

推荐答案

但这将始终将您的集合转换为可能不想要的Array.

But that would always convert your collection to an Array which may not be intended.

通过将lhs限制为可扩展的集合类型,可以将相同的类型用作返回值.这样,就不会隐式地进行任何转换,并且可以更高效地实现添加.

By restricting the lhs to an extensible collection type, the same type can be used as return value. This way, no conversion takes place implicitly and the addition could be implemented more efficiently.

如果您不希望转换为数组,则始终可以明确地执行此操作:Array(lhs) + rhs.

If you do not care for the conversion to an Array, you can always do that explicitly: Array(lhs) + rhs.

更多推荐

添加未在Swift的标准库中实现的SequenceType

本文发布于:2023-11-29 01:07:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644677.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:库中   标准   Swift   SequenceType

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!