Adding SequenceTypes not implemented in Swift'

2019-06-14 11:25发布

问题:

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:

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

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.

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