Array capacity property in Swift


In this tutorial, you are going to learn about Array capacity property in Swift programming with the help of some examples.

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

Below is given the syntax of the array capacity property:

array.capacity

In the above syntax, array is a literal for an array.

Example 1: Simple example of capacity property

var fruits = ["Apple", "Banana", "Mango", "Orange"]

// Get number of elements
var getResult = fruits.capacity

print(getResult)

Output:

4

As you can see in the above program, the output result is 4. This is because the number of elements in our fruits array is 4.

Example 2: Applying capacity to an empty array

Let’s see what happens if we apply the capacity property to an empty array:

var fruits = [String]()

// Get number of elements
var getResult = fruits.capacity

print(getResult)

Output:

0

As you can see, when we use it with an empty array, it returns 0. This is because an empty array doesn’t have any elements.

Example 3: Using capacity with if…else statement

You can also use the capacity property with if...else statement just as you can see in the example below:

var fruits = ["Apple", "Banana", "Mango", "Orange"]

if (fruits.capacity < 3) {

  print("The array has less than 3 elements")
}

else {

  print("The array has more than 3 elements")
}

Output:

The array has more than 3 elements