Junior — Middle
How to determine the correct key type for use in a dictionary?
sobes.tech AI
Answer from AI
In iOS (Swift), a dictionary key must conform to the Hashable protocol. This means that the key must be able to compute a hash value and be compared for equality, so that the dictionary can efficiently store and look up values.
For example, standard types such as String, Int, UUID already conform to Hashable and are suitable for use as keys.
If you create a custom type for a key, you need to implement the Hashable protocol:
struct User: Hashable {
let id: Int
let name: String
}
var dict: [User: String] = [:]
dict[User(id: 1, name: "Alice")] = "Developer"
Therefore, the correct key type is a type that:
- conforms to
Hashable; - has unique values for keys to avoid collisions;
- is immutable (preferably use structures or immutable properties).