Swift: Counting Elements in a Dictionary

Updated: May 8, 2023 By: Khue Post a comment

Counting dictionary elements

In Swift, you can count the number of elements in a given dictionary by using the count property. This property returns the total number of key-value pairs in the dictionary.

Example:

// programming languages and their year of creation
var languages = ["Swift": 2012, "C": 1972, "Java": 1995]
print(languages.count)

Output:

3

Checking if a dictionary is empty

To check whether a dictionary is empty, you can use the count property with an if...elsestatement like so:

// employees and their salaries
var employees = ["Wolf Boy": 4000, "Dragon Lady": 5000, "Demon Man": 6000]
if employees.count > 0 {
    print("There are \(employees.count) employees")
} else {
    print("There are no employees")
}

Output:

There are 3 employees

Another way to determine the emptiness of a dictionary is by using the isEmpty property:

var myDict = [String: String]()

if(myDict.isEmpty){
    print("Dictionary is empty")
}else{
    print("Dictionary is not empty")
}

Output:

Dictionary is empty