A type that provides an integer hash value.
- Xcode 6.0.1+
- Swift Standard Library
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 provide a hash value by default. Your own custom types can be hashable as well. When you define an enumeration without associated values, it gains
Hashable conformance automatically, and you can add
Hashable conformance to your other custom types by adding a single
A hash value, provided by a type’s
hash property, is an integer that is the same for any two instances that compare equally. That is, for two instances
b of the same type, if
a == b, then
a. The reverse is not true: Two instances with equal hash values are not necessarily equal to each other.
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. The
Hashable protocol inherits from the
Equatable protocol, so you must also satisfy that protocol’s requirements.
A custom type’s
Equatable requirements are automatically synthesized by the compiler when you declare
Hashable conformance in the type’s original declaration and your type meets these criteria:
struct, all its stored properties must conform to
enum, all its associated values must conform to
enumwithout associated values has
Hashableconformance even without the declaration.)
To customize your type’s
Hashable conformance, to adopt
Hashable in a type that doesn’t meet the criteria listed above, or to extend an existing type to conform to
Hashable, implement the
hash property in your custom type. To ensure that your type meets the semantic requirements of the
Equatable protocols, it’s a good idea to also customize your type’s
Equatable conformance to match.
As an example, consider a
Grid type that describes a location in a grid of buttons. Here’s the initial declaration of the
You’d like to create a set of the grid points where a user has already tapped. Because the
Grid type is not hashable yet, it can’t be used as the
Element type for a set. To add
Hashable conformance, provide an
== operator function and a
hash property in this example combines the hash value of a grid point’s
x property with the hash value of its
y property multiplied by a prime constant.
Grid conforms to the
Hashable protocol, you can create a set of previously tapped grid points.