Map Array of objects to 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
Converting an array of objects to a dictionary is a common Swift operation for fast lookups by key. Swift provides Dictionary(uniqueKeysWithValues:) for arrays with guaranteed unique keys, Dictionary(grouping:by:) for grouping multiple elements under each key, and the reduce(into:) method for custom transformations. The right choice depends on whether keys are unique and what structure you need in the result.
Using Dictionary(uniqueKeysWithValues:)
Transform the array into key-value tuples, then construct the dictionary:
This crashes at runtime if the array contains duplicate keys. Only use it when you are certain keys are unique.
Handling Duplicate Keys
Use Dictionary(_:uniquingKeysWith:) to resolve conflicts when keys may repeat:
Grouping with Dictionary(grouping:by:)
When multiple elements share a key, group them into arrays:
The result type is [String: [Product]] — each key maps to an array of matching elements.
Using reduce(into:)
For custom dictionary construction logic:
reduce(into:) is more efficient than reduce for building collections because it mutates in place rather than copying.
Converting Back to Array
Dictionaries are unordered. Sort explicitly when order matters.
Real-World Example
Common Pitfalls
- Using
uniqueKeysWithValueswith duplicate keys: This causes a runtime crash (Fatal error: Duplicate values for key). If keys might repeat, useDictionary(_:uniquingKeysWith:)to specify a merge strategy. - Forgetting that dictionaries are unordered: When you convert an ordered array to a dictionary, the insertion order is not guaranteed when iterating. If order matters, use
sorted()on the dictionary or keep a separate ordered collection. - Using
reduceinstead ofreduce(into:)for building dictionaries:reducecopies the accumulator dictionary on each iteration, resulting in O(n^2) performance.reduce(into:)mutates in place and runs in O(n). - Force-unwrapping dictionary lookups:
dict[key]!crashes if the key does not exist. Use optional binding (if let value = dict[key]) or provide a default withdict[key, default: defaultValue]. - Not using
\.keyPathsyntax: Instead of{ $0.category }, Swift supports\.categoryin many contexts. Key path expressions are more readable and less error-prone than closure syntax for simple property access.
Summary
- Use
Dictionary(uniqueKeysWithValues:)with.map { (key, value) }when keys are guaranteed unique - Use
Dictionary(_:uniquingKeysWith:)to handle duplicate keys with a merge strategy - Use
Dictionary(grouping:by:)to group multiple elements under each key - Use
reduce(into:)for custom dictionary construction — it is more efficient thanreduce - Dictionaries are unordered — sort explicitly when iteration order matters
- Always handle optional dictionary lookups safely with
if letor default values

