Junior — Middle
Millised tingimused ja omadused peavad objektidel olema, et neid saaks kasutada sõnastiku võtmeks?
sobes.tech AI
Vastus AI-lt
To be usable as a key in a dictionary (for example, in NSDictionary or Swift Dictionary), an object must meet the following conditions:
- Hashable: the object must have a correctly implemented hash calculation method (
hashin Swift,hashValueorhash(into:)), so that the dictionary can quickly find the key. - Equality comparison: the object must correctly implement the equality comparison method (
isEqualin Objective-C,Equatablein 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 in the fields involved in hash calculation and comparison, so that keys remain stable in the dictionary.