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