實例屬性
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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。