【问题标题】:underestimatedCount in Swift's DictionarySwift 词典中的 underestimatedCount
【发布时间】:2016-12-30 23:26:11
【问题描述】:

根据文档,Swift 的Dictionary 类型有这个名为underestimatedCount 的属性:

一个小于或等于元素个数的值 收藏。

有人知道为什么这在维斯特洛有用吗??!

让我困惑...

【问题讨论】:

标签: swift dictionary collections


【解决方案1】:

总结:从技术上讲,underestimatedCount 属于Sequence,并被CollectionDictionary 继承。 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 已经对这些集合的增长有了很好的了解。

【讨论】:

    猜你喜欢
    • 2019-10-24
    • 2020-05-04
    • 2015-12-12
    • 2020-05-17
    • 1970-01-01
    • 2019-01-28
    • 2022-12-09
    • 2016-01-01
    • 2021-10-09
    相关资源
    最近更新 更多