添加未在Swift的标准库中实现的SequenceType [英] Adding SequenceTypes not implemented in Swift's standard library

查看:292
本文介绍了添加未在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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