Sling Academy
Home/Swift/Swift: Counting Elements in a Dictionary

Swift: Counting Elements in a Dictionary

Last updated: May 08, 2023

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

Next Article: Swift: Access and Update Values in a Dictionary

Previous Article: Creating Dictionaries in Swift (with Examples)

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)
  • Swift: 5 Ways to Iterate over an Array