Generic Initializer

init(_:)

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

Declaration

init<H>(_ base: H) where H : Hashable

Parameters

base

A hashable value to wrap.

Discussion

The following example creates two type-erased hashable values: x wraps an Int with the value 42, while y wraps a UInt8 with the same numeric value. Because the underlying types of x and y are different, the two variables do not compare as equal despite having equal underlying values.

let x = AnyHashable(Int(42))
let y = AnyHashable(UInt8(42))

print(x == y)
// Prints "false" because `Int` and `UInt8` are different types

print(x == AnyHashable(Int(42)))
// Prints "true"