Swift Collection低估了使用量

什么是集合underestimateCount的用例。 文档说它具有与标准收集计数相同的复杂性。

我已经看到了它的声明:

 /// Returns a value less than or equal to the number of elements in /// `self`, *nondestructively*. /// /// - Complexity: O(N). public func underestimateCount() -> Int 

但它并没有告诉我什么时候应该使用它,什么原因。

underestimateCount实际上是Sequence协议的一个要求,并且有一个只返回0 的默认实现 :

 public var underestimatedCount: Int { return 0 } 

但是,对于提供自己的underestimatedCount实现的序列,这对于需要序列长度下限的逻辑非常有用,而不必迭代它(请记住Sequence不能保证非破坏性迭代)。

例如, Sequence上的map(_:)方法( 请参见此处的实现 )使用underestimateCount以便为结果数组保留一个初始容量:

  public func map<T>( _ transform: (Iterator.Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) // ... 

这允许map(_:)最小化反复附加到result的成本,因为已经为其分配了一个初始内存块(尽pipe在任何情况下值得注意的是ContiguousArray具有指数增长策略,追加费用)。

但是,对于CollectionunderestimateCount 的默认实现实际上只是返回集合的count

 public var underestimatedCount: Int { // TODO: swift-3-indexing-model - review the following return numericCast(count) } 

这将是符合RandomAccessCollection集合的O(1)操作,否则为O(n)。

因此,由于这个默认实现,直接使用CollectionunderestimatedCount count显然不如使用Sequence的常见,因为Collection保证非破坏性迭代,在大多数情况下, underestimatedCount count只会返回count

当然,自定义集合types可以提供它们自己的underestimatedCount count实现 – 以比它们的count实现更有效的方式给出它们包含的元素的下限,这可能是有用的。

(由于我提出的重复目标有些过时)

在Swift 3中,方法underestimateCount()已经被计算的属性underestimatedCount所取代。 我们可以看看为后者Collection的源代码:

  /// A value less than or equal to the number of elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. public var underestimatedCount: Int { // TODO: swift-3-indexing-model - review the following return numericCast(count) } /// The number of elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. public var count: IndexDistance { return distance(from: startIndex, to: endIndex) } 

它显然underestimatedCountcount只是使用count符合Collectiontypes(除非这些types实现自己的版本的underestimatedCount count )。