I'm trying to make a dictionary with the key as a struct I've created and the value as an array of Ints. However, I keep getting the error:
Type 'DateStruct' does not conform to protocol 'Hashable'
I'm pretty sure I've implemented the necessary methods but for some reason it still doesn't work.
Here's my struct with the implemented protocols:
struct DateStruct { var year: Int var month: Int var day: Int var hashValue: Int { return (year+month+day).hashValue } static func == (lhs: DateStruct, rhs: DateStruct) -> Bool { return lhs.hashValue == rhs.hashValue } static func < (lhs: DateStruct, rhs: DateStruct) -> Bool { if (lhs.year < rhs.year) { return true } else if (lhs.year > rhs.year) { return false } else { if (lhs.month < rhs.month) { return true } else if (lhs.month > rhs.month) { return false } else { if (lhs.day < rhs.day) { return true } else { return false } } } } }
Can anybody please explain to me why I'm still getting the error?
You can use any type that conforms to the Hashable protocol in a set or as a dictionary key. Many types in the standard library conform to Hashable : Strings, integers, floating-point and Boolean values, and even sets are hashable by default.
In Swift, a Hashable is a protocol that provides a hashValue to our object. The hashValue is used to compare two instances. To use the hashValue , we first have to conform (associate) the type (struct, class, etc) to Hashable property.
To conclude, a hashable protocol allows us to create custom types that can be compared for it's equality using it's hashValue . In this way we are able to use our custom type in a set or as a key in a dictionary while ensuring that it has a unique value.
NSObjectProtocol doesn't inherit from Hashable .
You're missing the declaration:
struct DateStruct: Hashable {
And your ==
function is wrong. You should compare the three properties.
static func == (lhs: DateStruct, rhs: DateStruct) -> Bool { return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day }
It's possible for two different values to have the same hash value.
Btw
var hashValue: Int
is obsolete (except in the legacy NSObject inheritance trees).
func hash(into hasher: inout Hasher) { hasher.combine(year); hasher.combine(month) ...
is the new way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With