AnyHashable
A type-erased hashable value.
@frozen struct AnyHashable
The AnyHashable
type forwards equality comparisons and hashing operations to an underlying hashable value, hiding the type of the wrapped value.
Where conversion using as
or as?
is possible between two types (such as Int
and NSNumber
), 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 AnyHashable
instances:
let descriptions: [AnyHashable: Any] = [
42: "an Int",
43 as Int8: "an Int8",
["a", "b"] as Set: "a set of strings"
]
print(descriptions[42]!) // prints "an Int"
print(descriptions[42 as Int8]!) // prints "an Int"
print(descriptions[43 as Int8]!) // prints "an Int8"
print(descriptions[44]) // prints "nil"
print(descriptions[["a", "b"] as Set]!) // prints "a set of strings"
Note that 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.
Citizens in Swift
Conformances
protocol CustomDebugStringConvertible
A type with a customized textual representation suitable for debugging purposes.
protocol CustomReflectable
A type that explicitly supplies its own mirror.
protocol CustomStringConvertible
A type with a customized textual representation.
protocol Equatable
A type that can be compared for value equality.
protocol Hashable
A type that can be hashed into a
Hasher
to produce an integer hash value.
Members
init<H>(H
) Creates a type-erased hashable value that wraps the given instance.
var base: Any
The value wrapped by this instance.
var customMirror: Mirror
var debugDescription: String
var description: String
var hashValue: Int
static func == (AnyHashable, AnyHashable
) -> Bool Returns a Boolean value indicating whether two type-erased hashable instances wrap the same value.
func hash(into: inout Hasher
)