Middle
Wat moet er gedaan worden zodat de gebruikersstructuur een sleutel wordt in het woordenboek?
sobes.tech AI
Antwoord van AI
Het is noodzakelijk om het protocol Hashable te implementeren.
Het protocol Hashable erft van Equatable.
Equatable: Vereist de implementatie van de gelijkheidoperator==om twee instanties van een structuur te vergelijken.Hashable: Vereist de implementatie van de eigenschaphash(into:), die de hash-waarde voor een structuur-instantie berekent.
Voorbeeld van implementatie:
struct Coordinate: Hashable {
let x: Int
let y: Int
// MARK: - Equatable
static func == (lhs: Coordinate, rhs: Coordinate) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
// MARK: - Hashable
func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
}
// Gebruik in een woordenboek
let coordinatesDictionary: [Coordinate: String] = [
Coordinate(x: 0, y: 0): "Origin",
Coordinate(x: 1, y: 1): "Point (1,1)"
]
print(coordinatesDictionary[Coordinate(x: 0, y: 0)]!)
Hasher wordt gebruikt om de hash-waarde te genereren. De methode combine accepteert verschillende hashbare waarden en combineert ze om de uiteindelijke hash te maken.