ProgrammingSwift Developer

How do data structures Dictionary work in Swift? What implementation features should be considered for optimal usage, and what difficulties may arise when storing and processing complex keys?

Pass interviews with Hintsage AI assistant

Answer.

Dictionary is an associative container in Swift that stores key-value pairs. Keys must conform to the Hashable and Equatable protocols to ensure uniqueness and constant time access to elements.

Features:

  • Keys must be unique.
  • Access, insertion, and deletion occur in amortized O(1).
  • Using complex keys is possible if Hashable and Equatable are explicitly implemented.

Example:

struct EmployeeID: Hashable { let company: String let id: Int } var employees: [EmployeeID: String] = [ EmployeeID(company: "A", id: 1): "Alice", EmployeeID(company: "B", id: 2): "Bob" ] let empName = employees[EmployeeID(company: "A", id: 1)] // Alice

Tricky Question.

Can Dictionary accept a user-defined type that does not implement Hashable as a key?

— Incorrect. If a type does not implement Hashable, it cannot be used as a key. Attempting to do so will result in a compilation error.

Example:

class Foo {} var dict: [Foo: Int] = [:] // Error: Foo does not implement Hashable

Examples of real errors due to ignorance of the topic's nuances.


Story

In a project, keys of the Dictionary were based on structures with arrays inside. The structure did not conform to the Hashable protocol, causing the Dictionary to not work. Solution: implement a custom hashValue that considers all fields, including arrays.


Story

Used NSObject subclasses as keys, relying on the object’s address. After rewriting part of the code to structures, the data no longer matched: hash values of structures were calculated differently, leading to lost data accessibility.


Story

When storing a dictionary with a complex key, forgot to implement Equatable. The result — elements with identical parameters were considered different keys, causing duplicates and errors during dictionary searches.