How to Check if key and value exist in swift with example

This tutorial explains how to check the key and value that exists in a Dictionary in Swift.

Dictionary is a data storage in swift to store keys and values.

Let’s declare a dictionary with a key of Int and a value of String

let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]

How to find if the key exists in a dictionary or not in Swift

In Swift, Dictionary[key] returns Optional value if exists else returns nil.

emp[11] != nil returns true if key exists in dictionary, else return false, not exists in dictionary

import Foundation;

let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]

// check key 11 exists in Dictionary
let keyExists = emp[11] != nil
print(keyExists)
if(keyExists ){
  print("Key 11 not exists in Dictionary")
}

// check key 1 exists in Dictionary
let keyExists1 = emp[1] != nil
print(keyExists1)
if(keyExists1 ){
  print("Key 1 exists in Dictionary")
}

Output:

false
true
Key 1 exists in Dictionary

Check if the dictionary Contains value or not in Swift

dictionary.values return the list of values, call contains the method to check if the value exists or not.

It returns true if a value exists, else returns false.

Here is an example to check if the dictionary contains a value or not in swift.

import Foundation;

let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]

print(emp.values.contains("john")) // true
print(emp.values.contains("john1")) // false

Output:

true
false