Swift Dictionary capacity

In this tutorial, we will learn about the Swift Dictionary capacity property with the help of examples.

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


var languages = ["Swift": 2012, "C": 1972, "Java": 1995]

// count total number of elements in languages var result = languages.capacity
print(result) // Output: 3

capacity Syntax

The syntax of the dictionary capacity property is:


Here, dictionary is an object of the Dictionary class.

capacity Return Values

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

Example 1: Swift Dictionary capacity

var nameAge = ["Alcaraz": 18, "Sinner": 20, "Nadal": 34]

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



In the above example, since

  • nameAge contains three key/value pairs, the property returns 3.
  • employees is an empty dictionary, 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 employees = ["Sabby": 1001, "Patrice": 1002, "Ranjy": 1003 ]

// true because there are only 3 elements in employees if (employees.capacity < 5) {
print("Small Company") } else { print("Large Company") }


Small Company

In the above example, we have created the dictionary named employees with 3 key/value pairs.

Here, since there are 3 key/value pairs in the dictionary, numbers.capacity < 5 evaluates to true, so the statement inside the if block is executed.

Did you find this article helpful?