Swift: Using keys and values

Using keys and values of Swift’s Dictionary:

What if we didn’t have to loop through a dictionary’s keys and values in Swift? We can create collections of a dictionary’s keys and values using the properties .keys and .values, which we can then loop through.

The .keys property stores dictionary keys, while the .values property stores dictionary values.

For example:

var vegetablesStand = [
  "Tomato": 21,
  "Onion": 18,
  "Radish": 8
];
print(vegetablesStand.keys);

The following keys will be printed by the print() statement in the above snippet:

["Onion", "Tomato", "Radish"]

If we printed vegetablesStand.values, we’d get the following results:

[18, 8, 21]

These properties can be used to specify how a dictionary should be iterated through.

For example, if we only need the names of the vegetables to create a list of what we sell, we can iterate through just the keys of vegetablesStand by appending .keys to the dictionary name:

for fruit in vegetablesStand.keys {
  print(fruit);
}

This would result in something like this:

Onion
Radish
Tomato

To find the total number of vegetables in stock, we could append .values to vegetablesStand and loop through the values in our dictionary:

var count = 0;
 
for vegetablesStock in vegetablesStand.values {
  count += vegetablesStock;
}
 
print(count);  // Prints: 47

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: