skip to content

In Swift, why does a set of mixed-type idempotency keys need `Set<AnyHashable>` rather than `Set<any Hashable>`?

level: middleimportance: should knowfreq 38%

answer

  1. boxes do not conform
  2. a concrete struct that conforms
  3. forwards equality and hashing
  4. canonical numbers, base and as?

basics

~20 s

any Hashable is an existential box, and the box does not conform to Hashable, so it cannot be a Set element. AnyHashable is a concrete standard-library struct that conforms to Hashable and forwards equality and hashing to the wrapped value.

solid answer

~40 s

`Set` needs an element type that conforms to `Hashable`. `any Hashable` is an existential, and an existential does not conform to its own protocol, so `Set<any Hashable>` fails with "type 'any Hashable' cannot conform to 'Hashable'". `AnyHashable` is the standard library's eraser for `Hashable`: a real struct that conforms, wraps any hashable value, and forwards `==` and hashing to it. Read a key back with `base` and `as?`. Equality is canonical rather than by dynamic type: `AnyHashable(42)` equals `AnyHashable(42 as Int8)` and `AnyHashable(42 as NSNumber)`, but not `AnyHashable("42")`. Two cautions: its hash values may change between standard-library releases, and its `Sendable` conformance is explicitly unavailable, so a `Sendable` type cannot store one in Swift 6 language mode.

code

swift · 19 lines
swift
import Foundation

// Idempotency keys of mixed types in one set.
var seenKeys: Set<AnyHashable> = []

let merchantID = 42             // Int
let terminalCode: Int8 = 42     // Int8, same numeric value
let requestToken = UUID()

print(seenKeys.insert(AnyHashable(merchantID)).inserted)    // true
print(seenKeys.insert(AnyHashable(terminalCode)).inserted)  // false: equal to Int 42
print(seenKeys.insert(AnyHashable(requestToken)).inserted)  // true
print(seenKeys.insert(AnyHashable("42")).inserted)          // true: a String is not an Int

let stored: AnyHashable = 42
if let id = stored.base as? Int {
    print("merchant", id)                                   // merchant 42
}
print(seenKeys.count)                                       // 3

go deeper

for a junior

Recall that AnyHashable lets one Set or Dictionary hold keys of different hashable types, and that you get a key back by casting its base property with as?.

for a middle

Explain why any Hashable cannot be a key, because the box does not conform to Hashable, and how AnyHashable forwards equality and hashing to the wrapped value.

for a senior

Know the edges: numeric canonicalisation makes Int 42 equal Int8 42, the generic Set insert can trap on that, hashes are unstable, and the type is not Sendable.

for a principal

Push for typed keys, such as an enum of key kinds, in new APIs, and keep AnyHashable at boundaries where the key types really are open, such as Objective-C-bridged dictionaries.

## Why `any Hashable` is not enough `Set` and `Dictionary` require their element or key type to conform to `Hashable`. `any Hashable` is an **existential** box, and an existential does not conform to its own protocol. `Hashable` inherits from `Equatable`, whose `==` compares two values of the same `Self` type, and two boxes may hold different types. So `Set<any Hashable>` is rejected with `type 'any Hashable' cannot conform to 'Hashable'`. Swift 5.7 made it legal to *write* `any Hashable` as a type, but it did not make the box conform. That is why `[any Hashable]` compiles, since an array places no `Hashable` requirement on its elements, while a set element or a dictionary key does. ## What `AnyHashable` is `AnyHashable` is a concrete `@frozen` struct in the standard library, a **type eraser** for `Hashable`. Its documentation says it "forwards equality comparisons and hashing operations to an underlying hashable value, hiding the type of the wrapped value". Because it is a real type that conforms to `Hashable`, it can be a set element or a dictionary key: - `AnyHashable(_:)` wraps any `Hashable` value, and the compiler converts a `Hashable` value to `AnyHashable` implicitly where one is expected, as in a `[AnyHashable: Any]` literal. - `base` returns the wrapped value as `Any`; cast it back with `as?`. A cast straight from the `AnyHashable`, `key as? Int`, also works. - A value already boxed as `any Hashable` converts with `AnyHashable(box)`, because the generic initializer opens the box (implicit opening, Swift 5.7). The implicit conversion does not apply to a box: `let key: AnyHashable = box` is rejected, so write the initializer. - Foundation uses it for open-ended keys, such as `Notification.userInfo`, typed `[AnyHashable: Any]?`. ## Equality is canonical, not by dynamic type `AnyHashable` does not simply treat different types as different keys. Where `as` or `as?` can convert between two types, such as `Int` and `NSNumber`, it compares a **canonical representation**; the standard library documents that `AnyHashable(42)` equals `AnyHashable(42 as NSNumber)`, and its own example finds the `Int` key `42` with the lookup `descriptions[42 as Int8]`. With Swift 6.4: - `AnyHashable(42) == AnyHashable(42 as Int8)` is `true`; - `AnyHashable(1) == AnyHashable(1.0)` is `true`; - `AnyHashable(42) == AnyHashable("42")` is `false`, because a `String` is not a number. The documentation also warns that bridged counterparts with different equality rules, such as two `NSString` values that differ only in Unicode normalization, can compare equal once wrapped. For idempotency keys that is usually what you want: two producers that send the same merchant number in different integer widths collapse to one key. ## Traps worth knowing 1. **The generic `insert(_:)` can trap.** `Set` has an extension for `Element == AnyHashable` with `insert<ConcreteElement: Hashable>(_:)`, which returns `memberAfterInsert` typed as the argument's type by force-casting the stored member's `base` with `as!`. If the set already holds the `Int` 42 and you insert an `Int8` 42, the stored member is equal but is an `Int`, so the cast to `Int8` traps at run time. Writing `insert(AnyHashable(terminalCode))` selects the ordinary `insert(_:)`, which returns `inserted == false`. 2. **Hash values are not stable.** The documentation says the hash encoding may change between any two releases of the standard library, so never persist them. 3. **Not `Sendable`.** The standard library declares `AnyHashable`'s `Sendable` conformance unavailable, because the wrapped value could be anything. A `Sendable` struct or class that stores an `AnyHashable` property is an error in Swift 6 language mode and a warning in Swift 5 mode. ## When to choose something else | Need | Prefer | |---|---| | Keys of a fixed, known set of kinds | an enum with associated values that conforms to `Hashable` | | Keys of one type | that concrete type, or a generic `Key: Hashable` | | Truly open, mixed keys, often from Objective-C APIs | `AnyHashable` | A `[AnyHashable: Any]` dictionary also gives up static typing on its values, so code that receives one usually converts it into a typed model at the boundary instead of passing it deeper. An enum spells out the key kinds, can be `Sendable`, and avoids canonicalisation surprises; `AnyHashable` is the right tool when the key types really are open. Writing `Hashable` conformances themselves, with `hash(into:)`, is covered with equality and hashing.

  • Why can `seenKeys.insert(terminalCode)` crash on a `Set<AnyHashable>` that already holds the `Int` 42?
    Passing an `Int8` picks the generic `insert(_:)` from the standard library's extension on `Set where Element == AnyHashable`. It returns `memberAfterInsert` as an `Int8` by force-casting the stored member's `base` with `as!`. The stored member is the equal `Int` 42, so that cast traps. `insert(AnyHashable(terminalCode))` uses the ordinary overload and returns `false`.
  • Can a `Sendable` struct store an `AnyHashable` property?
    Not cleanly. The standard library marks `AnyHashable`'s `Sendable` conformance unavailable, since the wrapped value may not be `Sendable`. Such a property is an error in Swift 6 language mode and a warning in Swift 5 mode. Use a concrete `Hashable & Sendable` key type or an enum of the key kinds instead.

  • Set<any Hashable> works because Swift 5.7 unlocked existentials for every protocol.
  • AnyHashable compares dynamic types first, so Int 42 and Int8 42 are different keys.
  • AnyHashable hash values are stable and safe to persist between launches.
  • AnyHashable is Sendable because every Hashable value it wraps is a value type.
  • Inserting a plain Int8 into a Set<AnyHashable> can never trap.

Assumes Swift 6.4 in Swift 6 language mode for the Sendable rule: storing AnyHashable in a Sendable type is an error there and a warning in Swift 5 mode.