Swift Array capacity

The capacity property returns the number of elements of the array without allocating any additional storage.

Example

var languages = ["Swift", "C", "Java"]

// check if leanguages is empty or not var result = languages.capacity
print(result) // Output: 3

capacity Syntax

The syntax of the array capacity property is:

array.capacity 

Here, array is an object of the Array class.


capacity Return Values

The capacity property returns the total number of elements present in the array without allocating any additional storage.


Example 1: Swift Array capacity

var names = ["Gregory", "Perry", "Nadal"]

// capacity total elements on names print(names.capacity)
var employees = [String]()
// capacity total elements on employees print(employees.capacity)

Output

3
0

In the above example, since

  • names contain three string elements, the property returns 3.
  • employees is an empty array, the property returns 0.

The capacity property here returns a total number of elements without allocating new storage.


Example 2: Using capacity With if...else

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// false because there are 10 elements on numbers if (numbers.capacity < 5) {
print("The array size is small") } else { print("The array size is large") }

Output

The array size is large

In the above example, we have created the array named numbers with 10 elements.

Here, since there are 10 elements in the array, numbers.capacity < 5 evaluates to false, so the statement inside the else block is executed.

Did you find this article helpful?