Array to dictionary

Jorge supervises a sorting machine. A conveyor belt moves boxes: those without an ID fall into a discard bin, while boxes with UUID labels continue and are placed on a shelf.

Table of contents


Problem

When working with lists of models (e.g., results, events, or users), we often need O(1) access by identifier for lookups, merges, or deduplication.

However, in many domains the id may be optional (UUID?) until the backend assigns it. If we build a dictionary directly, two frictions arise:

  • We need to filter out elements without ID to avoid invalid entries.
  • We must guarantee uniqueness of keys or the Dictionary(uniqueKeysWithValues:) constructor will fail at runtime if there are duplicates.

Solution

We extend Array (when its elements are Identifiable with ID == UUID?) to expose toDictionary().
The function uses compactMap to discard elements without ID and builds the dictionary with Dictionary(uniqueKeysWithValues:).

Precondition: existing IDs must be unique within the collection. If you expect collisions, consider a variant with Dictionary(_, uniquingKeysWith:) to resolve duplicates.

extension Array where Element: Identifiable, Element.ID == UUID? {
    func toDictionary() -> [UUID: Element] {
        Dictionary(uniqueKeysWithValues: self.compactMap {
            guard let id = $0.id else { return nil }
            return (id, $0) }
        )
    }
}

Notes:

  • Elements with id == nil are not included.
  • Key-based access is O(1) and simplifies in-memory merges/joins.

Result

A small, clear helper to convert from an array to a map by ID:

  • Faster to query O(1).
  • Safer: avoids inserting elements without identifier.
  • More expressive and reusable in services and view models.

Keep coding, keep running 🏃‍♂️