Creating dictionaries
The easiest way to create a dictionary is by using a dictionary literal. This is a list of key-value pairs separated by commas, enclosed in square brackets.
For your card game from the last chapter, instead of using the two arrays to map players to their scores, you can use a dictionary literal:
var namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6] print(namesAndScores)
// > ["Craig": 8, "Anna": 2, "Donna": 6, "Brian": 2]
In this example, the type of the dictionary is inferred to be [String: Int]. This means namesAndScores is a dictionary with strings as keys and integers as values.
When you print the dictionary, you see there’s no particular order to the pairs. Remember that, unlike arrays, dictionaries are unordered!
The empty dictionary literal looks like this: [:]. You can use that to empty an existing dictionary like so:
namesAndScores = [:]
or create a new dictionary, like so:
var pairs: [String: Int] = [:]
The type annotation is required here, as the type of the dictionary cannot be inferred from the empty dictionary literal.