Swift Dictionary capacity

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

Example

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:

dictionary.capacity 

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)

Output

3
0

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") }

Output

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.