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)
}
}
}
如果这样做,还可以添加字典(另请参见:添加SequenceTypes)
不在标准库中实现此功能有什么好处?
从Xcode 7开始,beta 5ExtensibleCollectionType
被重命名(并重组)为RangeReplaceableCollectionType
。因此,符合此协议的意图更加明确:
新协议仅要求此方法完全符合它:
mutating func replaceRange<C : CollectionType where C.Generator.Element == Generator.Element>(subRange: Range<Self.Index>, with newElements: C)
这对于任何无序集合都没有多大意义,因为此操作是不可预测的(在某些情况下,元素计数除外)。同样,高度依赖索引的默认实现和其他要求对于此类集合也没有太大用处。
总之,范围的插入和替换应该是可预测的,并保留其他元素的结构/顺序。因此Dictionaries
,任何其他无序集合都不应符合此特定协议。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句