Swift: Check if a key exists in a dictionary

Updated: May 8, 2023 By: Goodman Post a comment

This concise, example-based article walks you through a couple of different approaches to checking whether a key exists in a Swift dictionary.

Using the keys property and the contains() method

Example:

var myDict = [
    "name": "John Doe",
    "age": "99",
    "job": "iOS Developer"
]

// check the key "name"
if(myDict.keys.contains("name")){
    print("The key 'name' exists in myDict")
} else {
    print("The key 'name' does not exist in myDict")
}

Output:

The key 'name' exists in myDict

Using the subscript syntax

Example:

let animals = ["cat": "meow", "dog": "woof", "cow": "moo"]

// check the key "dog"
if animals["dog"] != nil {
    print("The dictionary has a dog")
} else {
    print("The dictionary does not have a dog")
}

Output:

The dictionary has a dog

Using the index(forKey:) method

Example:

let data = ["name": "John Doe", "gender": "male", "job": "iOS Developer"]

// check if the key "name" exists
if data.index(forKey: "name") != nil {
    print("The key \"name\" exists")
} else {
    print("The key \"name\" does not exist")
}

Output:

The key "name" exists