Swift – Check if Specific Key is Present in Dictionary
Welcome to Swift Tutorial. In this tutorial, we will learn how to check if a specific key is present a Swift Dictionary.
To check if a specific key is present in a Swift dictionary, check if the corresponding value is nil or not.
let keyExists = myDictionary[key] != nil
If myDictionary[key] != nil
returns true, the key is present in this dictionary, else the key is not there.
You can assign the result to a variable like keyExists
in the above syntax, and use for any other conditional checks.
Example 1 – Check if Key is not present in Swift Dictionary
In this example, we shall create a dictionary with some initial values and try to check if a new key is present in the dictionary or not.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
let keyExists = myDictionary["Surya"] != nil
if keyExists{
print("The key is present in the dictionary")
} else {
print("The key is not present in the dictionary")
}
Output
The key is not present in the dictionary
Example 2 – Check if Key is present in Swift Dictionary
In this example, we shall take a dictionary with some initial values and try to check if an existing key is present in the dictionary or not.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
let keyExists = myDictionary["John"] != nil
if keyExists{
print("The key is present in the dictionary")
} else {
print("The key is not present in the dictionary")
}
Output
The key is present in the dictionary
Conclusion
In this Swift Tutorial, we have learned how to check if a specific key is present in a Swift Dictionary with the help of example programs.