swift Array capacity Property



The capacity property of the array is used to check the capacity of the given array. Here the capacity represents the total number of elements an array can hold without allocating new memory. The capacity of the array can be larger than the count/length of the array. This additional capacity enables us to perform append operations without reallocating the storage every time an element is added.

For example, we have an array = [12, 33, 56, 1, 66, 3]. Now using the capacity property we will find the capacity of the array that is 6.

Syntax

Following is the syntax for capacity property.

var capacity : Int {get}

Return value

This function returns the capacity of the array.

Now we will discuss the use of the capacity property with the help of the following examples:

Example 1

Swift program to find the capacity of the array with the help of capacity property.

import Foundation

// Array of string type
let language = ["Swift", "Python", "Java", "CSharp"]

// Finding the capacity of the array
let result1 = language.capacity

print("The capacity of the array is : \(result1)")

// Array of integer type
let number = [34, 5, 6, 3, 3, 22, 12, 1]

// Finding the capacity of the array
let result2 = number.capacity

print("The capacity of the array is : \(result2)")

Output

The capacity of the array is : 4
The capacity of the array is : 8

Example 2

Swift program to check the dynamic growth of the capacity. Here we will check the capacity of the array after appending the new elements.

import Foundation

var myArr = [3, 4, 3, 2]

let initalCapacity = myArr.capacity

print("Initial capacity of the array is:", initalCapacity)

myArr.append(3)
myArr.append(23)
myArr.append(12)

let newCapacity = myArr.capacity

print("Capacity after appending elements: ", newCapacity)

Output

Initial capacity of the array is: 4
Capacity after appending elements:  9

Example 3

Swift program to find the capacity of the array after removing 5 elements from it. Here we will check the capacity of the array after removing 5 elements. So the after removing 5 elements the capacity of the array is same.

import Foundation

var myArr = [33, 44, 13, 12, 34, 56, 77, 8, 45, 2, 3]

let initalCapacity = myArr.capacity

print("Initial capacity of the array is:", initalCapacity)

// Removing five elements
myArr.remove(at: 1)
myArr.remove(at: 2)
myArr.remove(at: 3)
myArr.remove(at: 4)
myArr.remove(at: 5)

let newCapacity = myArr.capacity

print("Capacity after removing 5 elements: ", newCapacity)

Output

Initial capacity of the array is: 11
Capacity after removing 5 elements:  11
Advertisements