Junior — Middle
How to implement the use of custom objects as keys when working with dictionaries?
sobes.tech AI
Answer from AI
To use custom objects as keys in dictionaries (for example, in Swift Dictionary), these objects must conform to the Hashable and Equatable protocols.
This means that the class or struct must implement methods for computing the hash value and checking object equality.
Example in Swift:
struct User: Hashable {
let id: Int
let name: String
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id
}
}
var dict: [User: String] = [:]
let user1 = User(id: 1, name: "Alice")
dict[user1] = "Admin"
In this example, the dictionary key is a User object, uniquely identified by id. Implementing hash(into:) and == allows for correct storage and retrieval of objects in the dictionary.