Instance Methodswift 6.0.1Swift
reserveCapacity(_:)
Reserves enough space to store the specified number of elements.
mutating func reserveCapacity(_ minimumCapacity: Int)
Parameters
- minimumCapacity
The requested number of elements to store.
If you are adding a known number of elements to an array, use this method to avoid multiple reallocations. This method ensures that the array has unique, mutable, contiguous storage, with space allocated for at least the requested number of elements.
Calling the reserveCapacity(_:)
method on an array with bridged storage triggers a copy to contiguous storage even if the existing storage has room to store minimumCapacity
elements.
For performance reasons, the size of the newly allocated storage might be greater than the requested capacity. Use the array’s capacity
property to determine the size of the new storage.
Preserving an Array’s Geometric Growth Strategy
If you implement a custom data structure backed by an array that grows dynamically, naively calling the reserveCapacity(_:)
method can lead to worse than expected performance. Arrays need to follow a geometric allocation pattern for appending elements to achieve amortized constant-time performance. The Array
type’s append(_:)
and append(contentsOf:)
methods take care of this detail for you, but reserveCapacity(_:)
allocates only as much space as you tell it to (padded to a round value), and no more. This avoids over-allocation, but can result in insertion not having amortized constant-time performance.
The following code declares values
, an array of integers, and the addTenQuadratic()
function, which adds ten more values to the values
array on each call.
var values: [Int] = [0, 1, 2, 3]
// Don't use 'reserveCapacity(_:)' like this
func addTenQuadratic() {
let newCount = values.count + 10
values.reserveCapacity(newCount)
for n in values.count..<newCount {
values.append(n)
}
}
The call to reserveCapacity(_:)
increases the values
array’s capacity by exactly 10 elements on each pass through addTenQuadratic()
, which is linear growth. Instead of having constant time when averaged over many calls, the function may decay to performance that is linear in values.count
. This is almost certainly not what you want.
In cases like this, the simplest fix is often to simply remove the call to reserveCapacity(_:)
, and let the append(_:)
method grow the array for you.
func addTen() {
let newCount = values.count + 10
for n in values.count..<newCount {
values.append(n)
}
}
If you need more control over the capacity of your array, implement your own geometric growth strategy, passing the size you compute to reserveCapacity(_:)
.
Other members in extension
Typealiases
typealias Index
The index type for arrays,
Int
.typealias Indices
The type that represents the indices that are valid for subscripting an array, in ascending order.
typealias Iterator
The type that allows iteration over an array’s elements.
Type members
init(
) Creates a new, empty array.
init<S>(S
) Creates an array containing the elements of a sequence.
init(arrayLiteral: Element...
) Creates an array from the given array literal.
init(repeating: Element, count: Int
) Creates a new array containing the specified number of a single, repeated value.
Instance members
var capacity: Int
The total number of elements that the array can contain without allocating new storage.
var count: Int
The number of elements in the array.
var customMirror: Mirror
A mirror that reflects the array.
var debugDescription: String
A textual representation of the array and its elements, suitable for debugging.
var description: String
A textual representation of the array and its elements.
var endIndex: Int
The array’s “past the end” position—that is, the position one greater than the last valid subscript argument.
var startIndex: Int
The position of the first element in a nonempty array.
subscript(Range<Int>
) -> ArraySlice<Element> Accesses a contiguous subrange of the array’s elements.
subscript(Int
) -> Element Accesses the element at the specified position.
func append(Element
) Adds a new element at the end of the array.
func append<S>(contentsOf: S
) Adds the elements of a sequence to the end of the array.
func distance(from: Int, to: Int
) -> Int Returns the distance between two indices.
func formIndex(after: inout Int
) func formIndex(before: inout Int
) func index(Int, offsetBy: Int
) -> Int Returns an index that is the specified distance from the given index.
func index(Int, offsetBy: Int, limitedBy: Int
) -> Int? Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.
func index(after: Int
) -> Int Returns the position immediately after the given index.
func index(before: Int
) -> Int Returns the position immediately before the given index.
func insert(Element, at: Int
) Inserts a new element at the specified position.
func remove(at: Int
) -> Element Removes and returns the element at the specified position.
func removeAll(keepingCapacity: Bool
) Removes all elements from the array.
func replaceSubrange<C>(Range<Int>, with: C
) Replaces a range of elements with the elements in the specified collection.
func withContiguousMutableStorageIfAvailable<R>((inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? func withContiguousStorageIfAvailable<R>((UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? func withUnsafeBufferPointer<R>((UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R Calls a closure with a pointer to the array’s contiguous storage.
func withUnsafeBytes<R>((UnsafeRawBufferPointer) throws -> R
) rethrows -> R Calls the given closure with a pointer to the underlying bytes of the array’s contiguous storage.
func withUnsafeMutableBufferPointer<R>((inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R Calls the given closure with a pointer to the array’s mutable contiguous storage.
func withUnsafeMutableBytes<R>((UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R Calls the given closure with a pointer to the underlying bytes of the array’s mutable contiguous storage.