Sobes.tech
Junior — Middle

What conditions and characteristics must objects have to be used as keys in a dictionary?

sobes.tech AI

Answer from AI

To be usable as a key in a dictionary (for example, in NSDictionary or Swift Dictionary), an object must meet the following conditions:

  • Hashability: the object must have a correctly implemented hash code calculation method (hash in Swift, hashValue or hash(into:)), so that the dictionary can quickly find the key.
  • Equatability: the object must correctly implement the equality comparison method (isEqual in Objective-C, Equatable in Swift), so that the dictionary can distinguish different keys.

For example, in Swift, to use a custom type as a key, you need to implement the Hashable and Equatable protocols:

struct Person: Hashable {
    let id: Int
    let name: String
}

var dict: [Person: String] = [:]
dict[Person(id: 1, name: "Alice")] = "Developer"

Thus, objects should be immutable with respect to the fields involved in hash calculation and comparison, so that keys remain stable in the dictionary.

What conditions and characteristics must objects have… - sobes.tech