> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Swift Dictionary

A Swift `Dictionary` is a generic, unordered collection that stores associations between keys of the same type and values of the same type. It is implemented as a hash table, requiring the `Key` type to conform to the `Hashable` protocol to guarantee key uniqueness and enable $O(1)$ average time complexity for lookups, insertions, and deletions.

## Type Signature and Initialization

The standard library defines a dictionary as `Dictionary<Key, Value>`, but the syntactic sugar `[Key: Value]` is the preferred convention.

```swift theme={"dark"}
// Explicit type declaration with an empty dictionary
var explicitDict: Dictionary<String, Int> = [:]

// Shorthand syntax (Preferred)
var shorthandDict: [String: Int] = [:]

// Initialization via dictionary literal
var initializedDict: [String: Int] = ["Alpha": 1, "Beta": 2]
```

## Accessing and Modifying Values

Dictionary lookups via subscripting always return an `Optional<Value>` because the requested key may not exist in the collection.

```swift theme={"dark"}
let dict = ["Alpha": 1]

// Returns Optional(1)
let value = dict["Alpha"] 

// Returns nil
let missingValue = dict["Gamma"] 

// Subscripting with a default fallback (returns non-optional Int)
let safeValue = dict["Gamma", default: 0] 
```

Mutations can be performed using subscript assignment or dedicated mutating methods. Methods provide the advantage of returning the previous value prior to the mutation.

```swift theme={"dark"}
var mutableDict = ["Alpha": 1]

// Subscript assignment (inserts or updates)
mutableDict["Beta"] = 2 

// Subscript deletion
mutableDict["Alpha"] = nil 

// Method-based update (returns Optional containing the old value, or nil if new)
let oldValue = mutableDict.updateValue(3, forKey: "Beta") 

// Method-based removal (returns Optional containing the removed value)
let removedValue = mutableDict.removeValue(forKey: "Beta")
```

## Iteration

Because dictionaries are unordered, iteration order is not guaranteed. Iterating over a dictionary yields a tuple containing the key and value.

```swift theme={"dark"}
let dict = ["Alpha": 1, "Beta": 2]

// Iterating over key-value tuples
for (key, value) in dict {
    print("\(key): \(value)")
}

// Accessing keys or values independently (returns Dictionary.Keys / Dictionary.Values)
let keys = dict.keys
let values = dict.values
```

## Value Semantics and Memory

Dictionaries in Swift are value types implemented as structs. They utilize a copy-on-write (CoW) optimization strategy. When a dictionary is assigned to a new variable or passed to a function, it shares the same memory reference as the original until a mutation occurs, at which point a deep copy is allocated.

To optimize memory allocations when the final size of a dictionary is known in advance, you can preallocate contiguous memory using the `reserveCapacity(_:)` method. This prevents the overhead of dynamic reallocation and rehashing during bulk insertions.

```swift theme={"dark"}
var largeDict: [Int: String] = [:]
largeDict.reserveCapacity(10_000) 
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Swift Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
