What is the use of Hashable and Equatable in Swift? When to use which? -
i know hashable inherited equatable, can give me example requires hashable, not equatable. thanks!
when conform hashable
, provide method returns hash value of self
.
when conform equatable
, provide method returns whether given object , self
equal.
they seem serve 2 different purposes, why hashable
inherit equatable
? because hash values 2 equal objects equal!
what can , can't hashable
, equatable
?
equatable
has more limited uses hashable
. can compare equality of 2 objects, , that's it.
for hashable
, because can number represents object, can kind of treat objects numbers. can compare objects: whether less than, greater than, or equal object, numbers:
if obja.hashvalue > objb.hashvalue
this means can sort objects hashable
.
last not least, can use hashable
objects keys maps! because maps' keys cannot duplicate, how can system check whether put duplicate item in it? uses hash values of keys!
Comments
Post a Comment