Swift 里 Array (三) Inspecting an Array

判断是否为空

使用的是Collection协议里isEmpty的判断。

  public var isEmpty: Bool {
    return startIndex == endIndex
  }

startIndex 总是返回 0

  public var startIndex: Int {
    return 0
  }

endIndex代码如下:

  @inlinable
  public var endIndex: Int {
    @inlinable
    get {
      return _getCount()
    }
  }

最终用到了_ContiguousArrayStorage类里的countAndCapacity 变量。

  internal var count: Int {
    get {
      return _storage.countAndCapacity.count
    }
    nonmutating set {
      _internalInvariant(newValue >= 0)

      _internalInvariant(
        newValue <= capacity,
        "Can't grow an array buffer past its capacity")

      _storage.countAndCapacity.count = newValue
    }
  }

确定长度

  /// The number of elements in the array.
  @inlinable
  public var count: Int {
    return _getCount()
  }

在确定isEmpty时提到过。

capacity

  /// The number of elements the buffer can store without reallocation.
  @inlinable
  internal var capacity: Int {
    return _storage.countAndCapacity.capacity
  }

用到了_ContiguousArrayStorage类里的countAndCapacity 变量。

posted on 2019-03-20 22:57  花老🐯  阅读(131)  评论(0编辑  收藏  举报

导航