I'd like to use a very simple tuple as a key:
(Int, Int)
Dictionary keys need to be Hashable. I've learnt.
But can't find how I make this simple tuple Hashable, and do struggle with protocol conformance at the best of times.
More profoundly, a CGPoint would solve my problems. It can be of this format, but is not hashable.
Is it possible to extend a CGPoint so it's hashable? If so, how?
EDIT: Image of Int variant of CGPoint choice.
Making conform to
Hashable
is not difficult for class, struct or enum. You just need to explicitly declare conformance toHashable
and define a propertyhashValue: Int
. Practically, thehashValue
needs to fulfill one simple axiom: if a == b then a.hashValue == b.hashValue.(To conform
Hashable
, you also need to make the typeEquatable
. In case ofCGPoint
, it is alreadyEquatable
.)An example to make
CGPoint
conform toHashable
:As
CGPoint
containsCGFloat
values, so,CGPoint
as Key of Dictionary may cause unexpected behavior based on the calculation error of binary floating-point system. You need to use it with extra caution.ADDITION
If you want to avoid some calculation error issue and can accept that the structure can only contain
Int
s, you can define your own struct and make it conform toHashable
:Not much more difficult than the code above, one more thing you need is just defining
==
operator for the struct. Please make it a try.