Adding SequenceTypes not implemented in Swift's standard library

末鹿安然 提交于 2019-12-10 11:57:00

问题


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.



来源:https://stackoverflow.com/questions/31140092/adding-sequencetypes-not-implemented-in-swifts-standard-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!