7
根据文档,Swift的Dictionary
类型具有该属性命名underestimatedCount
:小于或等于 集合中的元素的数量underestimatedCount在Swift的字典
的值。
有人知道为什么在Westeros上这被认为是有用的??!
令我感到困惑......
根据文档,Swift的Dictionary
类型具有该属性命名underestimatedCount
:小于或等于 集合中的元素的数量underestimatedCount在Swift的字典
的值。
有人知道为什么在Westeros上这被认为是有用的??!
令我感到困惑......
摘要:从技术上来说,underestimatedCount
属于Sequence
,并且得到由Collection
和Dictionary
继承。 Dictionary
不会覆盖返回零的默认实现。
查看源代码,似乎underestimatedCount
被用作指示器,以确定一个可变集的生长的量,当新的项目被添加到它。
下面是从StringCore.Swift一个片段:
public mutating func append<S : Sequence>(contentsOf s: S)
where S.Iterator.Element == UTF16.CodeUnit {
...........
let growth = s.underestimatedCount
var iter = s.makeIterator()
if _fastPath(growth > 0) {
let newSize = count + growth
let destination = _growBuffer(newSize, minElementWidth: width)
相若方式,从StringCharacterView.swift:
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Iterator.Element == Character {
reserveCapacity(_core.count + newElements.underestimatedCount)
for c in newElements {
self.append(c)
}
}
甚至更好,从Arrays.swift.gyb:
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Iterator.Element == Element {
let oldCount = self.count
let capacity = self.capacity
let newCount = oldCount + newElements.underestimatedCount
if newCount > capacity {
self.reserveCapacity(
Swift.max(newCount, _growArrayCapacity(capacity)))
}
_arrayAppendSequence(&self._buffer, newElements)
}
奇怪的是,我只能找到一个用于的实现,在Sequence,并且那个返回零。
目前看来underestimatedCount
对集合/序列的自定义实现具有更多价值,对于标准的Swift集合,Apple对这些集合的增长已经有了一个好主意。
有一个[邮件列表讨论](https://www.mail-archive.com/[email protected]/msg00614.html),你不是第一个抱怨[坏文档】(https://bugs.swift.org/browse/SR-991) –