How to Check a Key in a Swift Dictionary and Get a Value: 5 Ways

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Check if a Key Exists in a Swift Dictionary and Retrieve the Value: A Complete Guide for Beginners and Pros

\n\n

Working with dictionaries is the daily bread of every iOS developer. But as soon as we move from simply "putting a value" to "does this key even exist?" — the real fun begins. This question has garnered thousands of views on Stack Overflow, and for good reason: a seemingly simple task hides several pitfalls.

\n\n

In this article, we won't just answer the question "Determining if Swift dictionary contains key and obtaining any of its values", but will break down 5 different approaches. You'll learn which method is faster, which is safer, and which is simply elegant code that's pleasant to write and read.

\n\n

Quick Primer: What is a Dictionary in Swift?

\n\n

For those just getting to know Swift: Dictionary is a collection of key-value pairs. Keys are unique, values can repeat. It looks like this:

\n\n
var userScores: [String: Int] = [\n    "Alice": 95,\n    "Bob": 87,\n    "Charlie": 92\n]
\n\n

Now imagine: you want to get the score for a player named "David". But David is not in the dictionary. If you simply write userScores["David"], Swift won't crash, but will return nil. And that's where the interesting part begins.

\n\n

Method #1: Classic if let — The Foundation Everyone Should Know

\n\n

The simplest and most readable way is to use optional binding via if let. You simultaneously check if the key exists and retrieve the value:

\n\n
let scores: [String: Int] = ["Alice": 95, "Bob": 87]\n\nif let aliceScore = scores["Alice"] {\n    print("Alice's score: \\(aliceScore)")\n} else {\n    print("Player not found")\n}
\n\n

Pros:

\n
    \n
  • Maximally readable code
  • \n
  • Safe handling of optionals
  • \n
  • No need to call additional methods
  • \n
\n\n

Cons:

\n
    \n
  • If you only need to check for the key's existence without getting the value, it's redundant
  • \n
\n\n

This approach is the gold standard for 90% of cases. It's exactly what Apple recommends in the official documentation.

\n\n

Method #2: Guard let — For Early Exit from a Function

\n\n

If you're writing a function where the absence of a key is a reason for an immediate exit, use guard let. This makes the code flat and eliminates the "pyramid of doom" from nested if statements:

\n\n
func printScore(for player: String, in scores: [String: Int]) {\n    guard let score = scores[player] else {\n        print("Player \\(player) not found")\n        return\n    }\n    // Here we are sure that score exists\n    print("Score for player \\(player): \\(score)")\n}\n\nprintScore(for: "Bob", in: ["Alice": 95, "Bob": 87]) // Score for player Bob: 87\nprintScore(for: "David", in: ["Alice": 95, "Bob": 87]) // Player David not found
\n\n

Pros:

\n
    \n
  • Clear separation between the "error path" and the "main scenario"
  • \n
  • The variable is available throughout the entire scope after guard
  • \n
\n\n

Cons:

\n
    \n
  • Not suitable if you just need to check for existence without exiting the function
  • \n
\n\n

Method #3: Checking via contains(where:) — When the Key Might Be Complex

\n\n

Sometimes you don't just need to find a key, but check it against some condition. For example, the key is a string, and you're looking for a partial match. This is where the contains(where:) method comes to the rescue:

\n\n
let config: [String: Any] = [\n    "app_version": "2.1.0",\n    "build_number": 42,\n    "is_debug_mode": true\n]\n\n// Look for a key that starts with "app_"\nlet hasAppKey = config.keys.contains { $0.hasPrefix("app_") }\nprint("Has app_ key: \\(hasAppKey)") // true\n\n// Get the value by the first found key\nif let appKey = confi                

Blogs

Book Recommendations