Skip to Content
Learn
Loops
The for-in Loop

Now that we can appreciate what loops do for us, let’s start with the for-in loop. Below is the general syntax:

for placeholderVariable in someSequence {
  for-in loop body
}

We use for-in loops to iterate over a sequence of values, such as Strings (which is a sequence of characters) or ranges (sequence of numbers). To create a range, we use the closed range operator (...) with a lower bound number and an upper bound number. For example, a range of 1...3 that has a lower bound of 1 and an upper bound of 3 contains the numbers: 1, 2, and 3.

Let’s say we wanted to use a for-in loop to iterate (repeat tasks) while going through the sequence of numbers 7, 8, and 9 represented by the range: 7...9.

print("Why is 6 afraid of 7? Because …") for num in 7...9 { print(num) }

Now let’s break down the example above:

  • The for keyword starts the loop.
  • num is a variable that holds the value of the current iteration. Notice that we don’t use a keyword like var to declare it — the Swift compiler does this for us. We can think of it as a placeholder, i.e. during the first iteration, the placeholder (num) has a value of 7.
  • The in keyword separates the placeholder from the sequence used for iteration.
  • 7...9 is a range containing the numbers 7, 8, and 9 and is the sequence we’re iterating over.
  • The for-in loop has a body enveloped by curly braces { }. The code inside the body gets executed for each iteration.

After taking the syntax into consideration, it would make sense that our code snippet prints out:

Why is 6 afraid of 7? Because … 7 8 9

Get it? 7 8 9! Cause 8 sounds like “ate”? So 7 “ate” 9!? … Alright, back to programming… 😅

Instructions

1.

Create a for-in loop that:

  • Uses age as the placeholder.
  • Iterates over the range from 1 to your current age using the closed range operator .... For example, if you’re 35 years old, then your range is 1...35.

Leave the body empty for now. There will be a warning even after you’ve passed this step, but it’ll go away once you complete the next step.

2.

We want our for-in loop to help us print out the last part of the Happy Birthday song.

Inside the block of the loop add a print() statement to print out:

Are you [age]?

Where [age] is replaced by the value of age in its current iteration.

Folder Icon

Take this course for free

Already have an account?