Sling Academy
Home/Swift/Swift: Check if a key exists in a dictionary

Swift: Check if a key exists in a dictionary

Last updated: May 08, 2023

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

Next Article: Swift: 5 ways to iterate over a dictionary

Previous Article: Swift: Removing a key-value pair from a dictionary

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)
  • Swift: 5 Ways to Iterate over an Array