Junior — Middle
How is hashing mechanics implemented and how does it work in data structures, ensuring uniqueness and quick access?
sobes.tech AI
Answer from AI
In data structures such as dictionaries or sets in Swift, hashing is used for quick access to elements.
How it works:
- Hash calculation: The object is transformed into an integer value (hash) that reflects its content.
- Placement in bucket: The hash is used to determine the position (bucket) in the internal data structure.
- Search and comparison: In case of collisions (same hashes), objects are compared for exact match.
This provides:
- Fast access (usually O(1)) to elements by key.
- Key uniqueness, as a check for hash and content match is performed when adding.
Example in Swift:
struct Person: Hashable {
var id: Int
var name: String
}
var dict = [Person: String]()
dict[Person(id: 1, name: "Alice")] = "Developer"
// Accessing dict[Person(id: 1, name: "Alice")] will quickly find the value
Here, the Hashable protocol requires implementing the hash(into:) method, which is responsible for hash calculation.