In this Swift programming tutorial, you are going to see how to check if a Swift dictionary contains a given key or not.
In this example, we will check if a specific key is present in our dictionary by checking if the corresponding value for that key is nil or not.
Below is the code to find if the value for a specific key is nil or not and assign it to a variable:
let keyExists = dictionaryName[key] != nil
If dictionaryName[key] != nil
is true, the key is present in the dictionary. if it returns false, the key is not present in the dictionary.
Now below is the code where we are using the if...else
statement to find out if the key is present in our dictionary or not:
var employeesSalary:[String:Int] = ["James":17500, "Maria":15200, "Robert":18900]
let keyExists = employeesSalary["Maria"] != nil
if keyExists {
print("The key is present")
} else {
print("The key is not present")
}
Output:
The key is present
In the above example, we have created a dictionary employeesSalary
and then store employeesSalary["Maria"] != nil
in the constant keyExists
.
Now let’s see another example. In this example, we will find out the presence of a key in the dictionary in a different way.
Here we will use the Swift keys.contains()
method to determine if a specific key exists or not in the dictionary.
Below is the code in Swift:
var employeesSalary:[String:Int] = ["James":17500, "Maria":15200, "Robert":18900]
var keyContains = employeesSalary.keys.contains("Maria")
if keyContains {
print("Key found")
} else {
print("Key not found")
}
Output:
Key found
In the above example, we have created the same dictionary as the previous one. But in this example, we are using the contains()
method to find if the key exists in the Swift dictionary.
We store the result in a variable keyContains
that returns true or false. If it returns true, that means the key is present in the dictionary, otherwise, it is not present.
We are using if...else
statement and printing different messages depending on the presence of the key.