StructureSwift5.9.0

    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

    Members

    Features