Using subscripting

Dictionaries support subscripting to access values. Unlike arrays, you don’t access a value by its index but rather by its key. For example, if you want to get Anna’s score, you would type:

namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]

// Restore the values

print(namesAndScores["Anna"])

// > Optional(2)

Notice that the return type is an optional. The dictionary will check if there’s a pair with the key Anna, and if there is, return its value. If the dictionary doesn’t find the

key, it will return nil.

print(namesAndScores["Greg"])

// > nil

Remember that with arrays, out-of-bounds subscript access caused a runtime error, but dictionaries are different since their results are wrapped in an optional.

You might not be aware of this yet, but subscript access with optionals is really powerful. It lets you find out if a specific player is in the game without needing to iterate over all the keys, as you must do when you use an array.

results matching ""

    No results matching ""