Adding SequenceTypes not implemented in Swift's standard library

时间:2015-06-30 13:48:49

标签: swift operator-overloading standard-library swift2

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

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?

1 个答案:

答案 0 :(得分:1)

但是,这总是会将您的集合转换为可能无意的数组。

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

如果您不关心转换为数组,您可以随时明确地执行此操作:Array(lhs) + rhs