What if we don’t need to loop through both the keys and the values of a dictionary? We can use the properties .keys
and .values
to create collections of the keys and values of a dictionary that we can then loop through.
The .keys
property stores a collection of dictionary keys, while the .values
property stores a collection of dictionary values.
For example:
var fruitStand = [ "Apples": 12, "Bananas": 20, "Oranges": 18 ] print(fruitStand.keys)
The print()
statement in the above snippet will output the following keys:
["Bananas", "Oranges", "Apples"]
If we printed fruitStand.values
, our output would include these values:
[20, 18, 12]
We can use these properties to specify how we want to iterate through a dictionary.
For example, if we only need the names of the fruits to create a list of what we sell, we can iterate through just the keys of fruitStand
by appending .keys
to the dictionary:
for fruit in fruitStand.keys { print(fruit) }
This would give us an output similar to this:
"Oranges" "Apples" "Bananas"
We could append .values
to fruitStand
to loop through the values of our dictionary and find out the total number of fruit we have in stock:
var total = 0 for fruitStock in fruitStand.values { total += fruitStock } print(total) // Prints: 50
Instructions
Underneath the declaration of total
, create a for
-in
loop that iterates only through the values of the dictionary lemonadeStand
.
Name the placeholder monthlyProfit
and leave the body of the for
-in
loop empty for now.
In the body of the loop, increase the value of total
by the value of monthlyProfit
.