总结:从技术上讲,underestimatedCount 属于Sequence,并被Collection 和Dictionary 继承。 Dictionary 不会覆盖返回零的默认实现。
看源码,underestimatedCount好像是用来作为一个指标来判断一个可变集合增加新项时的增长量。
这是来自StringCore.Swift的sn-p:
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 的一个实现,而那个实现返回零。
此时,underestimatedCount 似乎对集合/序列的自定义实现具有更大的价值,至于标准 Swift 集合,Apple 已经对这些集合的增长有了很好的了解。