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 arrays
var gnaam = ["Google", "Netflix", "Amazon", "Apple", "Facebook", "Meta"];
var letters = ["a", "b", "c", "d", "e"];
var numbers = [1, 2, 3];
// print number of elements
print(gnaam.capacity);
print(letters.capacity);
print(numbers.capacity);

Explanation

  • Lines 2–4: We create the arrays gnaam, letters, and numbers.
  • Line 7–9: We print the number of elements each array can contain without allocating new storage using the capacity property of arrays.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources