Swift Dictionary isEmpty

The isEmpty property checks if the dictionary is empty or not.

Example

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

// check if leanguages is empty or not var result = languages.isEmpty
print(result) // Output: false

isEmpty Syntax

The syntax of the dictionary isEmpty property is:

dictionary.isEmpty 

Here, dictionary is an object of the Dictionary class.


isEmpty Return Values

The isEmpty property returns:

  • true - if the dictionary does not contain any elements
  • false - if the dictionary contains some elements

Example 1: Swift dictionary isEmpty

var names = ["Alcaraz": 2003, "Sinner": 2000, "Nadal": 1985]

// check if names is empty or not print(names.isEmpty)
var employees = [String: Int]()
// check if employees is empty or not print(employees.isEmpty)

Output

false
true

In the above example, since

  • names contain three key/value pairs, the property returns false.
  • employees is an empty dictionary, the property returns true.

Example 2: Using isEmpty With if...else

var employees = ["Ranjy": 50000, "Sabby": 100000]

// false because names contains three key/value pairs if (employees.isEmpty) {
print( "Dictionary is empty") } else { print("Elements:", employees) }

Output

Elements: ["Ranjy": 50000, "Sabby": 100000]

Here, the employees dictionary is not empty, so the if block is skipped and the else block is executed.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges