Structure

AnyHashable

A type-erased hashable value.

Declaration

@frozen struct AnyHashable

Overview

The AnyHashable type forwards equality comparisons and hashing operations to an underlying hashable value, hiding its specific underlying type.

You can store mixed-type keys in dictionaries and other collections that require Hashable conformance by wrapping mixed-type keys in AnyHashable instances:

let descriptions: [AnyHashable: Any] = [
    AnyHashable("😄"): "emoji",
    AnyHashable(42): "an Int",
    AnyHashable(Int8(43)): "an Int8",
    AnyHashable(Set(["a", "b"])): "a set of strings"
]
print(descriptions[AnyHashable(42)]!)      // prints "an Int"
print(descriptions[AnyHashable(43)])       // prints "nil"
print(descriptions[AnyHashable(Int8(43))]!) // prints "an Int8"
print(descriptions[AnyHashable(Set(["a", "b"]))]!) // prints "a set of strings"

Topics

Initializers

init<H>(H)

Creates a type-erased hashable value that wraps the given instance.

Instance Properties

var base: Any

The value wrapped by this instance.

var customMirror: Mirror

The custom mirror for this instance.

var debugDescription: String

A textual representation of this instance, suitable for debugging.

var description: String

A textual representation of this instance.

var hashValue: Int

The hash value.

Instance Methods

func hash(into: inout Hasher)

Hashes the essential components of this value by feeding them into the given hasher.

Operator Functions

static func != (AnyHashable, AnyHashable) -> Bool

Returns a Boolean value indicating whether two values are not equal.

static func == (AnyHashable, AnyHashable) -> Bool

Returns a Boolean value indicating whether two type-erased hashable instances wrap the same type and value.

See Also

Type-Erasing Wrappers

struct AnySequence

A type-erased sequence.

struct AnyCollection

A type-erased wrapper over any collection with indices that support forward traversal.

struct AnyBidirectionalCollection

A type-erased wrapper over any collection with indices that support bidirectional traversal.

struct AnyRandomAccessCollection

A type-erased wrapper over any collection with indices that support random access traversal.

struct AnyIterator

A type-erased iterator of Element.

struct AnyIndex

A wrapper over an underlying index that hides the specific underlying type.