Swift – Check if Dictionary is Empty

To check if a Dictionary is empty in Swift, check isEmpty property of this Dictionary instance. isEmpty property returns a boolean value of true if the dictionary is empty, or false if the dictionary is not empty.

The syntax to check if Dictionary dict is empty is

</>
Copy
dict.isEmpty

We may use this property as a condition in Conditional Statements.

Examples

In the following program, we take an empty Dictionary, and programmatically check if this Dictionary is empty or not using isEmpty property.

main.swift

</>
Copy
var dict: [String:Int] = [:]
if dict.isEmpty {
    print("This Dictionary is empty.")
} else {
    print("This Dictionary is not empty.")
}

Output

This Dictionary is empty.
Program ended with exit code: 0

Now, let us take a Dictionary with some elements in it, and programmatically check if this dictionary is empty or not.

main.swift

</>
Copy
var dict: [String:Int] = ["apple": 24, "banana": 35]
if dict.isEmpty {
    print("This Dictionary is empty.")
} else {
    print("This Dictionary is not empty.")
}

Output

This Dictionary is not empty.
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to check if a Dictionary is empty or not using Dictionary.isEmpty property.