Swift Dictionary count

The count property returns the number of elements of the dictionary.

Example

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

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

count Syntax

The syntax of the dictionary count property is:

dictionary.count 

Here, dictionary is an object of the Dictionary class.


count Return Values

The count property returns the total number of elements present in the dictionary.


Example 1: Swift Dictionary count

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

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

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.

Example 2: Using count With if...else

var employees = ["Sabby": 1001, "Patrice": 1002, "Ranjy": 1003 ]

// true because there are only 3 elements on employees if (employees.count > 5) {
print("Large Company") } else { print("Small Company") }

Output

Small Company

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

Here, since there are only 3 key/value pairs in the dictionary, numbers.count > 5 evaluates to false, so the statement inside the else block is executed.

Did you find this article helpful?