Junior — Middle
Kuidas määrata õige võtmetüüp sõnastikus kasutamiseks?
sobes.tech AI
Vastus AI-lt
In iOS (Swift), the key for a dictionary 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 search for values.
For example, standard types like String, Int, UUID already implement Hashable and are suitable for use as keys.
If you create your own type for the 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 one that:
- implements
Hashable; - has unique values for keys to avoid collisions;
- is immutable (it's better to use structures or immutable properties).