Using Loops
In the last demo, you improved your calculator to decide which operation to perform based on the value of an input. You learned the difference between if-else and switch statements. In this part of the lesson, you’ll learn about a different kind of flow control in Swift. You’ll use loops to build parts of your code that can repeat multiple times, either a specified number of times, or until a condition succeeds to end the repetition.
Loops have a similarity to if statements. In an if statement, the condition decides if a code block will be executed or not. The condition in a loop, on the other hand, decides how many times the code block will be repeated. It could be once, twice, a thousand times or none at all.
Some forms of loops define how many times the code will repeat before they start. It’s as if you say: “Do this five times”. Other forms of loops repeat until something signals them to stop. Like: “Keep guessing numbers until you find the right one”. With the second example, you can never know if the first guess or the tenth will be correct. You just keep going.
for-in Loops
In Swift, you represent the first kind of loops with the keyword for:
let intArray = [1, 2, 3, 4, 5]
for index in intArray {
print("\(index)")
}
For loops are always tied to a sequence/array. You define a variable — in the example above that variable is named index — and each time through the code block, index equals the next item in the array. The example above prints the elements in intArray in order, each on a separate line.
while Loops
The other kind of loops, the ones that repeat an unknown number of times, come in two versions: while and repeat while. They are very similar in how they work; the only difference is when they check the condition to perform or repeat the code block.
while loops check a condition and keep executing the code block as long as the condition is true. The check is done first:
var number = 5 //1
while number < 10 { //2
print("\(number)") //3
number = number + 1
}
To break down the code in this example:
- The starting value of the variable
numberis5. - The
whileloop checks if the condition is true. It executes the code block as long asnumberholds a value smaller than 10. - The value of
numberis printed, and then it’s increased incrementally by one. This gets repeated until"9"is printed andnumberincreases to10.
When number has the value of 10, the condition written beside while is false because 10 isn’t smaller than 10. So the above code prints values from 5 to 9, each on a separate line.
If number starts with an initial value of 10, nothing is printed because while loops check the condition first before doing anything even for the first time.
On the other hand, repeat while executes the code block first, then checks the condition after the code has been executed.
var number = 5 //1
repeat {
print("\(number)") //2
number = number + 1
} while number < 10 //3
To break down the code in this example:
- The starting value of the variable
numberis5. - The value of
numberis printed, then it’s increased by one. - The
repeat whileloop checks if the condition is true. As long as it is, the loop will repeat the execution of the code block.
The block gets repeated until "9" is printed and number increases to 10. Then, the loop ends. This loop prints identical values to the previous while loop. However, if the initial value of number is 10, the print statement for number will execute and number will increase to 11.
This is because repeat while executes the code block at least once no matter what the condition is, but the while loop checks the condition first.
In different terms: while loops execute the code zero or more times, but repeat while loops execute the code one or more times.
Loop Breaks and Continues
There are two keywords you can use inside the code block of a loop that can interrupt the flow no matter the value of the loop’s condition. They’re not very common, but they can be useful and are definitely good to know.
Say you have an array of strings, each of which is a word. You’re writing an app that takes each word and checks how many letters are in it. The app only prints the words that have more than four letters and ignores the others. But if the word is "ABORT", the loop should stop and exit immediately. There are two ways to write this code. Here is the first:
var wordsArray = ["Hello", "silence", "my", "old", "friend", "I've" ,"come" ,"to" , "talk", "with", "you", "again", "ABORT", "Because", "a", "vision", "softly", "creeping"] //1
var index = 0 //2
while index < wordsArray.count && wordsArray[index] != "ABORT" { //3
if wordsArray[index].count > 4 { //4
print(wordsArray[index])
}
index = index + 1 //5
}
-
wordsArrayis an array of strings. It happens to have the first three lines of the song Sound of Silence, but it has the word"ABORT"inside it. -
indexis the variable you use to access the items in the array one by one. - A
whileloop checks thatindexisn’t out of range of the array and the string at that index doesn’t equal""ABORT". - The code block in the loop checks if the length of the string exceeds four letters, and if it does the block prints it. An else statement isn’t needed.
- You increment
indexso the loop uses the next string during the next iteration.
If you don’t increment index, your loop keeps repeating forever and your app seems like it’s frozen. But it’s actually doing the same thing over and over, which is printing "Hello".
Notice that the condition in the while loop is actually two conditions joined by two ampersand characters (&&). The && operator is a logical AND where both conditions must be true for the whole condition to be true. Another operator is ||, which signals OR — where only one of the two conditions must be true.
Note: Logical AND
&&will check the first condition before the second. If the first is false, it completely ignores the second and won’t execute it. Logical OR||is the opposite: It ignores the second condition if the first is true because the condition is thus true no matter what the value of the second. This is important to know because the second condition, if evaluated on the last iteration of the loop, causes a crash becausewordsArray[index]gives an out-of-bounds array. So the order of the two conditions here is important.
The code doesn’t look very pretty. Imagine you want to have more than one word to end the loop. You could add another && wordsArray[index] != clause. But soon, the while condition will start looking messy and harder to read and understand.
In this form, you’re also responsible for updating the index yourself. You could use a for loop to go through the array elements without worrying about going out of bounds. But then, how would you end the loop when you got to ABORT?
The answer is to write this loop by using the break and continue keywords. Both of them instruct the loop holding the code block to do something:
-
breakinstructs the loop to stop immediately. -
continueinstructs the loop to ignore the rest of the code in the block and start the next iteration.
The loop could look like this, using for and the two keywords:
for word in wordsArray { //1
if word == "ABORT" { //2
break
}
if word.count <= 4 { //3
continue
}
print(word) //4
}
- You’re using a regular
forloop. No need to track the index yourself. - Check if the word equals
"ABORT", and if it does then interrupt the loop withbreak. This skips the rest of the code block and ends the loop. - If the word has four or fewer characters, go to the next step in the
forloop without executing the rest of the code block. This skips theprintstatement. Remember you only want to print the words with more than four letters, so letters with four or less need to be skipped. Note that the operator<means less than and<=means less than or equal. - If the word was neither
"ABORT"nor had four or fewer characters, print it out.
The second version of the loop is much easier to read. Each if condition focuses on its part. One is responsible for exiting the loop, and the other is responsible for skipping the current word and moving to the next.
At the end, which loop to choose and how you want to organize your code is up to you. Just remember it’s not just about having code that works; it’s also about having code that is easy to read and to change in the future.
In the next demo, you’ll improve the code you wrote last lesson for the Fibonacci sequence to use loops.