实例属性
capacity
数组在不分配新存储的情况下可以包含的元素总数。
声明
var capacity: Int { get }
详述
每个数组都会保留特定数量的内存来保存其内容。当您向数组添加元素并且该数组开始超出其保留容量时,该数组会分配更大的内存区域并将其元素复制到新存储中。新存储是旧存储大小的倍数。这种指数增长策略意味着追加一个元素在恒定时间内发生,平均许多追加操作的性能。触发重新分配的追加操作有性能成本,但随着阵列变大,它们发生的频率越来越低。
下面的示例从一个数组字面量创建一个整数数组,然后附加另一个集合的元素。在追加之前,数组会分配足够大的新存储空间来存储结果元素。
var numbers = [10, 20, 30, 40, 50]
// numbers.count == 5
// numbers.capacity == 5
numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))
// numbers.count == 10
// numbers.capacity == 10
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相关用法
- Swift ContiguousArray contains(_:)用法及代码示例
- Swift ContiguousArray contains(where:)用法及代码示例
- Swift ContiguousArray compactMap(_:)用法及代码示例
- Swift ContiguousArray forEach(_:)用法及代码示例
- Swift ContiguousArray insert(contentsOf:at:)用法及代码示例
- Swift ContiguousArray reserveCapacity(_:)用法及代码示例
- Swift ContiguousArray lexicographicallyPrecedes(_:)用法及代码示例
- Swift ContiguousArray elementsEqual(_:)用法及代码示例
- Swift ContiguousArray isEmpty用法及代码示例
- Swift ContiguousArray suffix(from:)用法及代码示例
- Swift ContiguousArray endIndex用法及代码示例
- Swift ContiguousArray reduce(_:_:)用法及代码示例
- Swift ContiguousArray split(separator:maxSplits:omittingEmptySubsequences:)用法及代码示例
- Swift ContiguousArray sort()用法及代码示例
- Swift ContiguousArray firstIndex(of:)用法及代码示例
- Swift ContiguousArray replaceSubrange(_:with:)用法及代码示例
- Swift ContiguousArray first(where:)用法及代码示例
- Swift ContiguousArray append(contentsOf:)用法及代码示例
- Swift ContiguousArray randomElement(using:)用法及代码示例
- Swift ContiguousArray prefix(upTo:)用法及代码示例
- Swift ContiguousArray withUnsafeBufferPointer(_:)用法及代码示例
- Swift ContiguousArray index(_:offsetBy:limitedBy:)用法及代码示例
- Swift ContiguousArray joined(separator:)用法及代码示例
- Swift ContiguousArray prefix(through:)用法及代码示例
- Swift ContiguousArray subscript(_:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 ContiguousArray capacity。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。