Swift – Check if Dictionary is Empty
Welcome to Swift Tutorial. In this tutorial, we will learn how to check if a Swift Dictionary is empty.
To check if a dictionary is empty, you can either check if the size of the dictionary is zero or use the isEmpty function.
</>
Copy
var myDictionary:[keyType:valueType] = [:]
var isDictEmpty1 = myDictionary.count == 0
var isDictEmpty2 = myDictionary.isEmpty
The type of keys array is same as that of keyType
, and the type of values array is same as that of valueType
.
Example 1 – Check if dictionary empty using count Method
In this example, we shall check if the dictionary is empty using dictionary.count method.
main.swift
</>
Copy
var myDictionary:[String:String] = [:]
var isDictEmpty = myDictionary.count == 0
print("isDictEmpty: \(isDictEmpty)")
Output
isDictEmpty: true
Example 2 – Check if dictionary empty using isEmpty Method
In the following example, we shall check if the dictionary is empty using dictionary.isEmpty method.
main.swift
</>
Copy
var myDictionary:[String:String] = [:]
var isDictEmpty = myDictionary.isEmpty
print("isDictEmpty: \(isDictEmpty)")
Output
isDictEmpty1: true
Conclusion
In this Swift Tutorial, we have learned how to check if a dictionary is empty in Swift with the help of example programs.