Chapter 5: Loops

Loops are repeating blocks of code that we can use to perform one action to multiple pieces of data in Swift.


What you will learn

  • Writing your first repeat-while loop
  • Writing your first for-in loop
  • Writing your first for-each loop

Key Terms

  • Loop: a section of repeated code that repeats until a condition is met.
  • The DRY Principle: a programming principle meaning "Don't Repeat Yourself", in an effort to remind programmers to use the most efficient coding practice.

The DRY principle states "Don't Repeat Yourself". It is a coding principle that has existed for a long time, but loops in Swift are blocks of repeating code.

How can using loops be a good practice? While a loop repeats the same code over and over, it does so within the confines of a single loop. We can pass in data from an array, for example, and the same operation can be performed on each item of that collection.

This is a very useful component of the Swift language. We will learn about the 3 popular types of Swift 3 loops in this chapter. Let's get loopy! 🙃

Setting up a Playground

First, open Xcode if you haven't already and click Create New Playground. Give it a name like Loops and click Next. Choose somewhere to save this .playground file and click Create to save it. You should see a screen like the one in Figure 1.5.1.

Figure 1.5.1 Screen Shot 2016-10-10 at 5.01.11 AM.png

Delete all the boilerplate code on the left side but leave import UIKit as it is necessary.

Why you should use loops

Let's imagine that we have 4 employees working at our company. Each employee earns a different salary:

  • Employee 1: $45,000
  • Employee 2: $100,000
  • Employee 3: $54,000
  • Employee 4: $20,000 (Sorry, bro.)

Create 4 variables (one for each employee) and set the value of each variable to be the related salary above:

import UIKit

var employee1Salary = 45000.0
var employee1Salary = 100000.0
var employee1Salary = 54000.0
var employee1Salary = 20000.0

We just finished up Q4 of 2016 and we've had a very successful year. We want to give each employee a raise of 10%. In your Playground, type:

import UIKit

var employee1Salary = 45000.0
var employee1Salary = 100000.0
var employee1Salary = 54000.0
var employee1Salary = 20000.0

employee1Salary = employee1Salary + (employee1Salary * 0.10)

The above code performs the operation 45000.0 + (45000.0 * 0.10) as it takes our variables value and adds it to 10% of itself.

On the right-hand side of the Playground, you should see a new value – 49500.

Let's perform this operation for each employee:

employee1Salary = employee1Salary + (employee1Salary * 0.10) // prints 49500
employee2Salary = employee2Salary + (employee2Salary * 0.10) // prints 110000
employee3Salary = employee3Salary + (employee1Salary * 0.10) // prints 59400
employee4Salary = employee4Salary + (employee1Salary * 0.10) // prints 22000

I don't know about you, but I smell some stanky code. If you were thinking, "WAIT. We're repeating ourself... What if we had 100 employees?" Doing this operation for 100 employees would be very exhausting and likely would result in errors. We are also violating the DRY principle (Don't Repeat Yourself).

There is no need for us to have 4 separate variables for storing employee salaries. Let's instead consolidate them into a single array named salaries:

var salaries = [45000.0, 100000.0, 54000.0, 20000.0]

How can we cycle through these and add 10% to each person's salary? Well, we could type:

salaries[0] = salaries[0 + (salaries[0] * 0.10)

But that would result in the same issue. We still need to write a line of code for each employee and repeat ourself. Yuck! Delete that line of code leaving only the array called salaries.

How do we solve this problem? This is where loops in Swift become very useful. For each employee, we've given them a salary and need to perform the same operation on each one – salary + (salary * 10%). Let's write a loop to handle this.

Writing your first loop

The first loop we will write is called a repeat-while loop. There are a few different types of loop, but they all run code on repeat while or until a certain condition is met.

Writing a repeat-while loop

Below our salaries variable, type:

var salaries = [45000.0, 100000.0, 54000.0, 20000.0]

var x = 0
repeat {
    x += 1
} while (x < salaries.count)

You should see that on the right side of the Playground window our loop runs 4 times. But why?

We ask our loop to repeat taking the value of our variable x and adding one to it. Then our loop checks against the condition we declared: x < salaries.count. We ask it to see what the value of x is and then see if that is less than the total number of items in the array salaries. The .count following an array will give you the value of how many items there are in that array. If we look, there are 4 salaries so, therefore, salaries.count = 4.

So under the hood, we are doing the following:

var salaries = [45000.0, 100000.0, 54000.0, 20000.0]

var x = 0
x + 1 // Now x = 1
// Check condition: 1 < 4 is true, continue to loop

x + 1 // Now x = 2
// Check condition: 2 < 4 is true, continue to loop

x + 1 // Now x = 3
// Check condition: 3 < 4 is true, continue to loop

x + 1 // Now x = 4
// Check condition: 4 < 4 is false, stop looping

Adding the 10% salary equation

Now all we need to do is add our salary equation but instead of using a number value to call a specific element of our array (i.e. salaries[0]), we will use our variable x (i.e. salaries[x]) because it's value iterates from 0 up until 3 when run through our loop. Remember, in arrays in Swift use zero-indexing, meaning that the first element is numbered 0.

Add the following to your repeat-while loop:

var salaries = [45000.0, 100000.0, 54000.0, 20000.0]

var x = 0
repeat {
    salaries[x] = salaries[x] + (salaries[x] * 0.10)
    x += 1
} while (x < salaries.count)

The variable x could be named anything, but x is simply a common choice used in loops. A variable that is more wordy but also more descriptive is index. Remember that in an array, the index is the number used to identify each element in the array.

To be more descriptive, change the variable x to be index instead. Like so:

var salaries = [45000.0, 100000.0, 54000.0, 20000.0]

var index = 0
repeat {
    salaries[index] = salaries[index] + (salaries[index] * 0.10)
    index += 1
} while (index < salaries.count)

So what is this doing? We begin with our index variable set to 0. Then we declare a repeat-while loop. Inside the repeat block we add an equation which adds 10% of our salary to our current salary for the item at the index with the same value as our variable index (at this point, it's equal to 0). Then we add 1 to our index variable making it equal to 1. Finally, we check using our while condition to see if index is still less than the total number of elements in our salaries array.

It probably seems that I am repeating myself, but it is really important that you understand this.

Writing a for-in loop

Another type of loop that you may want to write at times is called a for-in loop. It enables you to loop through a range of values and perform an operation for each value.

Here is an example of a for-in loop:

for x in 1...5 {
    print("Index: \(x)")
}

If you type the above code into your Playground, you will see the result "(5 times)" meaning that we have looped 5 times. In the console at the bottom of the playground window, you should see this message:

Index: 1
Index: 2
Index: 3
Index: 4
Index: 5

The value of x is being set to a value of 1, then we print the message Index: 1 because x is equal to 1. The loop then restarts but this time x is set to the next value in the range: 2. The console prints Index: 2 and the loop repeats. This continues until we hit a value of 5.

The use of ... means "inclusive" and indicates that we should include every value from 1 until 5.

If we wanted to make it "exclusive" – so that our loop considers everything except the last value in the range – we would need to add a new "exclusive" loop as follows:

for x in 1...5 {
    print("Index: \(x)")
}

for x in 1..<5 {
    print("Exclusive Index: \(x)")
}

You should only see 4 lines print out for the second loop. This is because we have asked it to exclude the final value of 5 from being used.

The beginning of a for-in loop is indicated by the keyword for. Then we create a variable named x, but it could be named anything. Next, we use the keyword in to indicate that we are about to declare a range of values. At the end we state which values the loop should operate within.

To continue with out salaries example above, type the following for-in loop in your Playground window:

for i in 0..<salaries.count {
    salaries[i] = salaries[i] + (salaries[i] * 0.10)
    print(salaries[i])
}

This loop creates a variable named i and declares a range of 0 to "less-than" the value of salaries.count. Since salaries.count is equal to 4, our loop is exclusive and can only check values between 0 and 3 since 4 is not less than 4. This is perfect, however, because the index of our salaries array begins at zero and ends at 3.

The flow of the above loops goes like this: the variable i gets set to 0 – the first value in our range. Then i is passed in as the index for our salaries array. Afterward, we do the math to add a 10% raise like before. Finally, we print the raised salary to the console below.

Here is the key difference between a for-in loop and a repeat-while loop: in a for-in loop, the value of our placeholder variable (in this case i) is modified by the range of values we set at the end.

In a repeat-while loop, we need to increment the variable index by writing index += 1.

Creating a for-each loop

The next loop is for when you may have a variable number of items to loop through. We've used predefined ranges or an array with static information inside of it. What if all salary information was stored on a server which could change from day to day with new hires and fires? If we were to enter in everybody's salary information manually in a static array, it would be much harder to change or modify anyones salary. It also would be a troublesome task to locate a certain employee's salary if they were fired.

To write a for-each loop, type the following:

for salary in salaries {
    print("Salary: \(salary)")
}

As you can see in the console at the bottom of your Playgrounds window, every salary in our array is printed nicely.

The above code works by starting with the keyword for to indicate we are creating a loop. Then, we create a variable called salary and ask it to loop through each item in the salaries array until we reach the end. For each item loop through in the array we print it's value into a String like so: "Salary: 24200.0"

Personally, I find for-each loops the easiest for a beginner to understand as you can name the variable something specific related to the contents of your array.

Wrapping up

Loops are a foundational concept to understand when learning to code. If you feel confused about how they work, I encourage you to re-read this chapter. Try typing out the examples a few times. It's also a great idea to do some research online. Find examples and real-life scenarios where people are using loops and learn from them.

We've learned about repeat-while, for-in, and for-each loops in Swift. Now you can loop through collections of data and write better, more efficient code. Whenever you need to perform the same operation over and over, instead of writing multiple lines of almost duplicate code use a loop!

Exercise

Create an Array that stores the names of all four members of the Beatles. Write a for-each loop that walks through the Array and prints the name of each Beatles member.

Create another Array that stores four countries populations. Write a for-in loop that walks through the array and prints a sentence with the population value passed into the sentence using String Interpolation. The population is 12378932, for example.