Search code examples
swiftdictionarystandard-libraryswift2swift-protocols

Dictionary doesn't conform to ExtensibleCollectionType


Dictionaries in Swift don't conform to ExtensibleCollectionType. Since it would be easy to extend it (it somehow doesn't work with Swift 1.2; using Swift 2):

extension Dictionary: ExtensibleCollectionType {

    // ignoring this function
    mutating public func reserveCapacity(n: Int) {}

    mutating public func append(x: Dictionary.Generator.Element) {
        self[x.0] = x.1
    }

    mutating public func extend<S : SequenceType where S.Generator.Element == Dictionary.Generator.Element>(newElements: S) {
        for x in newElements {
            self.append(x)
        }
    }
}

If you do so Dictionaries can also be added (see also: Adding SequenceTypes)

Is there any benefit don't implementing this in the standard library?


Solution

  • As of Xcode 7 beta 5 ExtensibleCollectionType was renamed (and restructured) to RangeReplaceableCollectionType. So the intention conforming to this protocol is more clear:

    The new protocol only requires this method to fully conform to it:

    mutating func replaceRange<C : CollectionType where C.Generator.Element == Generator.Element>(subRange: Range<Self.Index>, with newElements: C)
    

    This wouldn't make much sense for any unordered collections since this operation isn't predictable (except for the element count in some cases). Also the default implementations and other requirements which highly rely on the index aren't that useful for such collections.

    In conclusion insertions and replacements of ranges should be predictable and preserve the structure/ordering of the other elements. Therefore Dictionaries and any other unordered collection shouldn't conform to this particular protocol.