- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 132字
- 2021-07-02 14:45:10
Dictionaries
Let's take a look at the definition of the Dictionary type:
public struct Dictionary<Key, Value> where Key : Hashable
In an array, you can only carry a single type of object, but there is no constraint on this type of object. Dictionaries can hold any Value, but the Key has to conform to the Hashable protocol. The reason is simple: in order to efficiently index a dictionary and compare two dictionary keys, Swift uses the hash value of the key, instead of the key itself. This also helps us to write a variety of dictionary types that can make our programs more expressive.
Many types conform to the Hashable protocol, and you can make your own types conform to this protocol if you need to create you own custom dictionary keys.