在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
发布评论