How to check if a dictionary is empty in Swift

Overview

The isEmpty property of a Dictionary instance allows us to see whether a dictionary is empty or not. An empty dictionary contains no key-value pairs.

Syntax

dictionary.isEmpty

Parameters

This function does not take any parameters.

Return values

The value returned is a Boolean. If it is empty, a true is returned, otherwise a false is returned.

Code example

// create dictionaries
var dict1 : [String: String] = [:]
var dict2 = [
"name": "Theodore",
"role": "Developer"
]
// check if empty
print(type(of : dict1), dict1.isEmpty)
print(type(of : dict2), dict2.isEmpty)

Code explanation

  • Lines 2 and 3: We create two dictionaries, dict1 and dict2.
  • Lines 9 and 10: We check what type of instance the dictionaries are. If they’re empty, we print the results returned.

Free Resources