Swift Dictionary - Count and Key Existence
In this article, we will explain how to get the number of key-value pairs in a Swift Dictionary and how to check if a key exists.
Getting the Number of Key-Value Pairs with count
To get the number of key-value pairs in a Swift Dictionary, use the count property.
var dict = ["Key1": "value1", "Key2": "value2", "Key3": "value3"]
print(dict.count)
The output is as follows. Since there are three key-value pairs, it prints 3.
3
Checking if a Dictionary is Empty with isEmpty
To check if a Swift Dictionary is empty, use the isEmpty property.
var dict = ["Key1": "value1", "Key2": "value2", "Key3": "value3"]
print(dict.isEmpty)
dict.removeAll()
print(dict.isEmpty)
The output is as follows. After calling removeAll(), the Dictionary becomes empty and dict.isEmpty returns true .
false
true
Checking if a Dictionary Contains a Key
To check if a Swift Dictionary contains a specific key, use the contains() method on the keys property.
For example, to check if the keys Key2 and Key4 exist in the Dictionary dict:
let dict = ["Key1": "value1", "Key2": "value2", "Key3": "value3"]
print(dict.keys.contains("Key2"))
print(dict.keys.contains("Key4"))
The output is as follows. Since Key2 exists, it returns true. Since Key4 does not exist, it returns false.
true
false
That wraps up how to get the number of key-value pairs in a Swift Dictionary and how to check if a key exists.