How to use AnyHashable in Swift

Issue #453

From documentation

A type-erased hashable value.

DiscussionThe AnyHashable type forwards equality comparisons and hashing operations to an underlying hashable value, hiding its specific underlying type.You can store mixed-type keys in dictionaries and other collections that require Hashable conformance by wrapping mixed-type keys in AnyHashable instances

1
2
3
4
5
6
7
8
9
10
let descriptions: [AnyHashable: Any] = [
AnyHashable("😄"): "emoji",
AnyHashable(42): "an Int",
AnyHashable(Int8(43)): "an Int8",
AnyHashable(Set(["a", "b"])): "a set of strings"
]
print(descriptions[AnyHashable(42)]!) // prints "an Int"
print(descriptions[AnyHashable(43)]) // prints "nil"
print(descriptions[AnyHashable(Int8(43))]!) // prints "an Int8"
print(descriptions[AnyHashable(Set(["a", "b"]))]!) // prints "a set of strings"

We don’t necessarily need to map from [AnyHashable: Any] to [String: Any], we can just access via string key

1
userInfo["aps"]

Comments