For Loops

In Swift, you can use a for loop to repeat code.

For example, let’s use a for loop to calculate the sum from 0 to 10:

var sum = 0

for n in 0...10 {
    sum = sum + n
}

print(sum)

Output:

55

Loops are extremely common in Swift and other programming languages.

As you can imagine, when working with data, you need to be able to repeatedly perform the same action on a bunch of instances.

Such actions include sorting a database, accumulating a sum, converting text to upper case, and so much more.

In this guide, you learn how to use a for loop to repeat code in Swift.

This chapter is part of a completely free Swift for Beginners guide. Make sure you have completed all the chapters from the start before reading this one.

Disclaimer: To learn Swift, you have to repeat everything you see in this guide and in the following guides. If you only read the guides, you are not going to learn anything!

For Loops in Swift

In programming, it is crucial to be able to repeat code.

For example, given an electronic list that represents the data of 10,000 festival-goers, your task could be to figure out all the food allergies.

Doing this manually would take forever.

However, thanks to looping, you can write a script and get the job done in a matter of minutes.

Loops are one of the basic building blocks of any scalable piece of software. When you develop iOS apps, you are going to use loops a lot.

The Naive Way to Looping

The naive way to repeat code is by copy-pasting the piece of code.

For example, let’s print numbers from 1 to 5 by copy-pasting a bunch of print() function calls:

print("1")
print("2")
print("3")
print("4")
print("5")

Output:

1
2
3
4
5

What if you now had to count numbers from 1 to 1,000,000?

In that case, it does not make sense to copy-paste the print() function calls the way we just did.

This is where you can use a loop.

In Swift, you have two types of loops:

  • For loops
  • While loops

In this chapter, we are going to focus on the for loops. (In the next chapter, you are going to learn while loops.)

In Swift, the syntax to creating a for loop is:

for count in start...end {
    // actions to repeat
}

Where:

  • for … in … begins a for loop.
  • count is a looping variable that increments as the loop goes on. You give it any name you like.
  • start is the value at which the loop starts counting.
  • end is the value at which the loop ends counting.
  • The curly brackets specify a block of code to be repeated. You can place any valid Swift code into it.

Chances are this sounds total nonsense to you.

The best way to learn loops is by playing with some examples.

Let’s start by repeating the example in which we counted from 1 to 5.

This time, let’s use a for loop instead of naively copy-pasting the code.

for count in 1...5 {
    print(count)
}

Output:

1
2
3
4
5

In this example, the looping variable count runs from 1 to 5. During each iteration, the current value of the count variable is printed to the console.

Let’s see another really similar example.

This time, let’s count from 5 to 10:

for i in 5...10 {
    print(i)
}

Output:

5
6
7
8
9
10

This time the looping variable was called i and it ran from 5 to 10 while printing the values.

This is to demonstrate that:

  • The looping variable can have any name you like.
  • The loop does not need to start from 1. It can start from anywhere as long as start < end.

Next, let’s see more examples of using for loops with slightly more advanced tasks.

More Examples: For Loops in Action

The best way to learn to code is by writing code.

Loops can be a confusing topic for you as a beginner.

Due to the importance of loops, it is really important you understand how they work and how to create one yourself.

Thus, you need to gain more experience with loops.

Here are 3 for loop examples.

Make sure to write, run and understand each example before proceeding to the next chapter.

Example 1: Print Even Numbers from 0 to 10

In the previous section, you incremented numbers with a for loop.

In this example, your task is to show only the even numbers between the range 0…10.

Feel free to try it yourself before looking down for an answer.

Here is a step-by-step solution to the problem.

To print even numbers from 0 to 10, we need a way to:

  1. Count from 0 to 10. This can be done using a for loop as you just learned.
  2. Check if a number is odd or even. You can use an if-statement with the modulo operator (%) to check if a number is divisible by 2.
  3. Display a number only if it is even. This is nothing new to you. You can use print() to show the number inside the if-statement.

Here is how it looks in code:

for number in 0...10 {
    if number % 2 == 0 {
        print(number)
    }
}

Output:

0
2
4
6
8

Let’s see another example.

Example 2: Calculate Compound Interest

Calculate the compound interest with the following information:

  • The initial investment is $1500.00.
  • The annual interest rate is 7%.
  • In addition to this, you deposit $200.00 annually at the end of each compounding period.

Your task is to calculate the amount of money the savings account has in 10 years.

Here is the solution.

This calculator does not use any complicated math equations.

Instead, we are going to simulate the years passing and the interest accumulating exactly the way it works in the real life.

This is what it looks in code:

// Info about the investment
let interest = 1.07
let yearly = 200.00
let nYears = 10

// Initial investment
var total = 1500.00

// Compound interest
for year in 1...nYears {
    total = 1.07 * total + yearly
}

print(total)

Output:

5714.016628190251

After 10 years, your bank account has a balance of ~$5700.00.

Awesome!

Let’s take a closer look at the code.

  1. You first created constants that represent the interest rate, yearly savings, and the number of years.
  2. You then store an initial amount of $1,500.00 in the bank account (a variable called total).
  3. Then you let the money do the work by simulating the passing years with a for loop.
    • The loop starts at the end of the first compounding period as 1 year has passed.
    • Each year, the total savings are multiplied by the interest rate to add 7% to the savings.
    • Then a new $200.00 is deposited.
  4. This process continues until the year is 10.

As you can see, you were already able to solve a complex problem with your Swift programming skills.

In the next example, you are going to see a best practice on what to do when you do not need the looping variable.

Example 3: Use the Looping Parameter as a Wildcard

If you paid close attention to the previous section, you may have noticed that we did not use the looping parameter year at all. It was only there because the loop would not work otherwise.

You also likely saw a yellow warning in the loop in your Xcode editor. This warning is about that unused looping variable.

Although it is just a warning, you should still fix it.

When you are not using the looping variable, use the wildcard parameter _.

A great example of this is when you use a for loop to repeat the same action:

for _ in 1...5 {
    print("Hello")
}

Output:

Hello
Hello
Hello
Hello
Hello

Later, you are going to see another common and related use case for the wildcard operator (_).

This completes the chapter on for loops in Swift. Before putting it all together, let me show you a quick teaser for the future.

Teaser: Loop Through an Array in Swift

Later in this series, you are going to learn how to use arrays to store items in the same place in your program.

One of the most common tasks related to arrays is to loop through them.

Thus, I am going to end this chapter with a little teaser.

Let’s use a for loop to iterate over an array of numbers and display each number in the console:

let numbers = [1, 2, 3, 4, 5]

for number in numbers {
    print(number)
}

Output:

1
2
3
4
5

Later in this series, there is a dedicated chapter for arrays.

Next Chapter: While Loops in Swift

Conclusion

In this guide, you learned how to repeat tasks in Swift using for loops.

To recap, repeating actions is commonplace in programming.

Instead of manually copy-pasting the lines of code you want to repeat, you can use a loop.

In this chapter, you learned how to use a for loop to repeat actions.

The for loop works such that it goes through a range of numbers from a start to an end. During each number, you can specify a block of code that gets executed.

For example, here is a for loop that counts from 1 to 5 in the console:

for count in 1...5 {
    print(count)
}

In the next chapter, you are going to learn how to repeat tasks with the other type of loop, that is, the while loop.

Next Chapter: While Loops in Swift