字典不符合 ExtensibleCollectionType

Dictionary doesn't conform to ExtensibleCollectionType

Swift 中的词典不符合 ExtensibleCollectionType。因为扩展它很容易(它在某种程度上不适用于 Swift 1.2;使用 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)
        }
    }
}

如果这样做,还可以添加词典(另请参阅:Adding SequenceTypes

不在标准库中实现它有什么好处吗?

从 Xcode 开始,7 beta 5 ExtensibleCollectionType 已重命名(并重组)为 RangeReplaceableCollectionType。所以遵守这个协议的意图更加明确:

新协议只要求此方法完全符合:

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

这对于任何无序集合都没有多大意义,因为此操作不可预测(某些情况下元素计数除外)。此外,高度依赖索引的默认实现和其他要求对此类集合没有多大用处。

总之,范围的插入和替换应该是可预测的,并保持其他元素的 structure/ordering。因此 Dictionaries 和任何其他无序集合不应符合此特定协议。