What is array.capacity in Swift?
Overview
In Swift, capacity is a property of an array. It gets the total number of elements that the array can contain without allocating new storage.
Syntax
arr.capacity
Parameters
This method takes no parameter.
Return Value
It returns an integer value.
Example
// create arraysvar gnaam = ["Google", "Netflix", "Amazon", "Apple", "Facebook", "Meta"];var letters = ["a", "b", "c", "d", "e"];var numbers = [1, 2, 3];// print number of elementsprint(gnaam.capacity);print(letters.capacity);print(numbers.capacity);
Explanation
- Lines 2–4: We create the arrays
gnaam,letters, andnumbers. - Line 7–9: We print the number of elements each array can contain without allocating new storage using the
capacityproperty of arrays.