字典不符合ExtensibleCollectionType

时间:2015-06-30 14:25:33

标签: swift dictionary standard-library swift2 swift-protocols

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

在标准库中没有任何好处吗?

1 个答案:

答案 0 :(得分:0)

从Xcode 7 beta 5开始,ExtensibleCollectionType被重命名(并重组)为RangeReplaceableCollectionType。所以符合这个协议的意图更清楚:

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

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

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

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