Hashable Interface
struct interface Hashable: Equatable {
pub hashValue: Int
}// Declare a structure named `Point` with two fields
// named `x` and `y` that have type `Int`.
//
// `Point` is declared to implement the `Hashable` interface,
// which also means it needs to implement the `Equatable` interface.
//
struct Point: Hashable {
pub(set) var x: Int
pub(set) var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
// Implementing the function `equals` will allow points to be compared
// for equality and satisfies the `Equatable` interface.
//
pub fun equals(_ other: {Equatable}): Bool {
if let otherPoint = other as? Point {
// Points are equal if their coordinates match.
//
// The essential components are therefore the fields `x` and `y`,
// which must be used in the implementation of the field requirement
// `hashValue` of the `Hashable` interface.
//
return otherPoint.x == self.x
&& otherPoint.y == self.y
} else {
return false
}
}
// Providing an implementation for the hash value field
// satisfies the `Hashable` interface.
//
pub synthetic hashValue: Int {
get {
// Calculate a hash value based on the essential components,
// the fields `x` and `y`.
//
var hash = 7
hash = 31 * hash + self.x
hash = 31 * hash + self.y
return hash
}
}
}Last updated