Skip to main content

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.

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)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.
// 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.
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.
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.
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.
var largeDict: [Int: String] = [:]
largeDict.reserveCapacity(10_000) 
Master Swift with Deep Grasping Methodology!Learn More