Dictionaries
A
Dictionary
is an
unordered collection of mappings/associations from keys to values. It is
very similar to a Set and has the same performance, but stores a key/value pair, and only the key has to be
Hashable
. It can be used for storing preferences, or when you have a group of named values that are either too many or change too often to be hardcoded. Then, you can use the names as keys.
The full name is
Dictionary<Key, Value>
, but it is more commonly written as
[Key: Value]
.
Dictionary ignores the order in which values are added or removed, and may change it arbitrarily, just like Set.
Working with Dictionaries
Here are a few basic operations with dictionaries:
Create a dictionary and print it to observe that the order is not preserved:
var numbers = [0: "zero", 1: "one", 10: "ten", 100: "one hundred"] print(numbers) // [100: "one hundred", 10: "ten", 0: "zero", 1: "one"]
Add or change a value:
numbers[20]...