A type-erased hashable value.
@frozen struct AnyHashable
AnyHashable type forwards equality comparisons and hashing operations to an underlying hashable value, hiding the type of the wrapped value.
Where conversion using
as? is possible between two types (such as
AnyHashable uses a canonical representation of the type-erased value so that instances wrapping the same value of either type compare as equal. For example,
AnyHashable(42) compares as equal to
AnyHashable(42 as NSNumber).
You can store mixed-type keys in dictionaries and other collections that require
Hashable conformance by wrapping mixed-type keys in
let descriptions: [AnyHashable: Any] = [ 42: "an Int", 43 as Int8: "an Int8", ["a", "b"] as Set: "a set of strings" ] print(descriptions!) // prints "an Int" print(descriptions[42 as Int8]!) // prints "an Int" print(descriptions[43 as Int8]!) // prints "an Int8" print(descriptions) // prints "nil" print(descriptions[["a", "b"] as Set]!) // prints "a set of strings"
AnyHashable does not guarantee that it preserves the hash encoding of wrapped values. Do not rely on
AnyHashable generating such compatible hashes, as the hash encoding that it uses may change between any two releases of the standard library.