protocol
Hashable
Inheritance |
Equatable
View Protocol Hierarchy →
|
---|---|
Import |
|
Instance Variables
The hash value.
Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution.
Declaration
var
hashValue
:
Int
{
get
}
Instance Methods
Returns a Boolean value indicating whether two values are equal.
Equality is the inverse of inequality. For any values a
and b
,
a == b
implies that a != b
is false
.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func
==(
lhs
:
Self
,
rhs
:
Self
) -
>
Bool
Declared In
Equatable
1 inherited item hidden. (Show all)
A type that provides an integer hash value.
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 toHashable
: strings, integers, floating-point and Boolean values, and even sets provide a hash value by default. Your own custom types can be hashable as well. When you define an enumeration without associated values, it gainsHashable
conformance automatically, and you can addHashable
conformance to your other custom types by adding a singlehashValue
property.A hash value, provided by a type's
hashValue
property, is an integer that is the same for any two instances that compare equally. That is, for two instancesa
andb
of the same type, ifa == b
thena.hashValue == b.hashValue
. The reverse is not true: Two instances with equal hash values are not necessarily equal to each other.Important: Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution.
Conforming to the Hashable Protocol
To use your own custom type in a set or as the key type of a dictionary, add
Hashable
conformance to your type by providing ahashValue
property. TheHashable
protocol inherits from theEquatable
protocol, so you must also add an equal-to operator (==
) function for your custom type.As an example, consider a
GridPoint
type that describes a location in a grid of buttons. Here's the initial declaration of theGridPoint
type:You'd like to create a set of the grid points where a user has already tapped. Because the
GridPoint
type is not hashable yet, it can't be used as theElement
type for a set. To addHashable
conformance, provide an==
operator function and ahashValue
property.The
hashValue
property in this example combines the hash values of a grid point'sx
andy
values using the bitwise XOR operator (^
). The^
operator is one way to combine two integer values into a single value.Note: Set and dictionary performance depends on hash values that minimize collisions for their associated element and key types, respectively.
Now that
GridPoint
conforms to theHashable
protocol, you can create a set of previously tapped grid points.