Swift
Dictionary
Key-Value
Coding
Programming

How can I get key's value from dictionary in Swift?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Swift dictionaries provide fast key-based lookup, but reading values correctly requires understanding optionals and type safety. Many runtime issues come from force unwrapping or incorrect assumptions about missing keys. A small set of safe patterns makes dictionary access predictable and clean.

Basic Lookup and Optional Result

Dictionary subscripting returns an optional because key may not exist.

swift
1var scores: [String: Int] = [
2    "Ava": 95,
3    "Noah": 88
4]
5
6let maybeScore = scores["Ava"]
7print(maybeScore as Any) // Optional(95)

For absent keys you get nil, not zero or empty value.

Safe Unwrapping with if let

Use optional binding when value might be missing.

swift
1if let score = scores["Mia"] {
2    print("Score: \(score)")
3} else {
4    print("No score found")
5}

This avoids crashes and makes missing-key behavior explicit.

Provide a Default Value

When fallback behavior is acceptable, use nil-coalescing.

swift
let score = scores["Mia"] ?? 0
print(score)

Choose default values carefully so they do not hide data issues.

Updating and Reading in One Place

default subscript helps for counters and grouped data.

swift
1var counts: [String: Int] = [:]
2counts["apple", default: 0] += 1
3counts["apple", default: 0] += 1
4print(counts["apple"] ?? 0) // 2

This pattern is concise and avoids repeated key-existence checks.

Accessing Nested Dictionaries

Nested lookup is common in JSON-like data structures.

swift
1let data: [String: [String: String]] = [
2    "user": ["name": "Ava", "city": "Toronto"]
3]
4
5let city = data["user"]?["city"] ?? "unknown"
6print(city)

Optional chaining keeps nested access safe and readable.

Iterating Keys and Values

If you need both keys and values, iterate using tuple syntax.

swift
for (name, score) in scores {
    print("\(name): \(score)")
}

For sorted output, sort keys before lookup.

swift
for name in scores.keys.sorted() {
    print("\(name): \(scores[name] ?? 0)")
}

Type-Safe API Design

When dictionaries back application state, wrap access in helper functions to enforce defaults and validation rules.

swift
1func value(for key: String, in map: [String: Int]) -> Int {
2    guard let v = map[key] else {
3        return -1
4    }
5    return v
6}

This centralizes access policy and reduces duplicated nil handling.

Updating, Removing, and Transforming Values

Dictionary access is not only about reads. Many workflows need atomic-style updates and safe removals.

swift
1var inventory: [String: Int] = ["book": 2, "pen": 5]
2
3inventory["book", default: 0] += 3
4let removed = inventory.removeValue(forKey: "pen")
5print(removed as Any)
6print(inventory)

removeValue returns an optional old value, which is useful for logging and undo flows.

You can also transform values while preserving keys:

swift
let doubled = inventory.mapValues { $0 * 2 }
print(doubled)

These APIs keep dictionary logic expressive without manual loops for simple transformations.

Working with JSON-Like Dictionaries

Dynamic payloads often use [String: Any], but this sacrifices compile-time safety. Prefer decoding to typed models where possible.

swift
1import Foundation
2
3struct User: Decodable {
4    let id: Int
5    let name: String
6}
7
8let json = "{\"id\":1,\"name\":\"Ava\"}".data(using: .utf8)!
9let user = try JSONDecoder().decode(User.self, from: json)
10print(user.name)

Typed decoding reduces runtime casting errors and improves maintainability for larger apps.

Common Pitfalls

  • Force unwrapping dictionary lookup results with ! when key may be missing.
  • Using fallback defaults that silently hide malformed input.
  • Assuming dictionary iteration order is stable.
  • Mixing value types through [String: Any] without validation.
  • Repeating nested optional checks instead of using optional chaining.

Summary

  • Swift dictionary lookup returns optionals by design.
  • Use if let, guard, or ?? for safe value access.
  • Use default subscript for counters and accumulation logic.
  • Optional chaining simplifies nested dictionary reads.
  • Encapsulate access rules in helpers for larger codebases.

Course illustration
Course illustration

All Rights Reserved.