Skip to main content
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.

Accessing and Modifying Values

Dictionary lookups via subscripting always return an Optional<Value> because the requested key may not exist in the collection.
Mutations can be performed using subscript assignment or dedicated mutating methods. Methods provide the advantage of returning the previous value prior to the mutation.

Iteration

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

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.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More