The capacity property returns the number of elements of the array without allocating any additional storage.
Example
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
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
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.