Swift: Iterating through a Dictionary

Iterating through a Dictionary in Swift:

We can use loops to iterate through all of the elements of a dictionary in Swift!

When we want to go through each individual key-value pair in a dictionary, this is useful. If we were the owners of a store, for example, we might want to double-check the stock on every item we sell.

If we wanted to use a forin loop to loop through every key and value in a dictionary, the syntax would be as follows:

for (keyHolder, valueHolder) in nameofdictionary {
  // Body of loop

Dictionaries have both keys and values, we group them together in parentheses () and separate them with a comma for our placeholder.

A tuple is a collection of two or more values enclosed in parentheses () and separated by commas ,. Visit Swift’s Documentation to learn more about tuples.

Let’s make a dictionary that keeps track of each student’s name and scores in a class. If we want to see each student’s name and scores, we can use the code below:

var scores = [
  "Alex": 99,
  "Liza": 87,
  "Mathew": 62,
  "Sandy": 88
for (Names, scores) in scores {
  print("\(Names) has \(scores) scores.")

We’d get the following output if we ran this code:

Liza has 87 scores.
Sandy has 88 scores.
Alex has 99 scores.
Mathew has 62 scores.

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: