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:
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
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
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.