Using properties and methods

Dictionaries, like arrays, conform to Swift’s Collection protocol. Because of that, they share many of the same properties. For example, both arrays and dictionaries have isEmpty and count properties:

Note: If you just want to know whether a dictionary has elements or not, it is always better to use the isEmpty property. A dictionary needs to loop through all of the values to compute the count. isEmpty, by contrast, always runs in constant time no matter how many values there are.

If you’d like to look only at the keys or the values of a dictionary, you can create an array from the dictionary’s keys or values properties, respectively:

Array(namesAndScores.keys) // ["Craig", "Anna", "Donna", "Brian"] Array(namesAndScores.values) // [8, 2, 6, 2]

In order to conserve processing and memory consumption, the keys and values properties actually return special lazy collection types. Because they conform to Swift’s Sequence type, you can iterate over them with a for loop. They are called lazy because the values only become available as your loop requests them. This is an important detail if you ever deal with dictionaries that have thousands or millions of keys and values. Often, however, just using standard, randomly accessible array is more convenient. The above example creates standard arrays from the key and value lazy collections.

These are regular arrays as you’ve learned about in the previous chapter.

results matching ""

    No results matching ""