Search⌘ K
AI Features

Looping Control Flow

Explore the essentials of looping control flow in Swift programming, including for-in loops for fixed iterations, while loops for conditional repetition, and repeat-while loops for executing code at least once. Understand how to use break and continue statements to manage loop execution effectively.

Looping vs. conditional control flow

Regardless of the programming language used, application development is largely an exercise in applying logic, and much of the art of programming involves writing code that makes decisions based on one or more criteria. Such decisions define which code gets executed, how many times it is executed, and conversely, which code gets by-passed when the program is executing. This is often referred to as control flow since it controls the flow of program execution. Control flow typically falls into the categories of looping control flow (how often code is executed) and conditional control flow (whether code is executed). The concepts covered in this section intend to provide an introductory overview of both types of control flow in Swift.

Looping control flow

We will begin by looking at control flow in the form of loops. Loops are essentially sequences of Swift statements that are to be executed repeatedly until a specified condition is met. The first looping statement we will explore is the for-in loop.

The Swift for-in statement

The for-in loop is used to iterate over a sequence of items contained in a collection or number range and provides a simple-to-use looping option.

The syntax of the for-in loop is as follows:

for constant name in collection or range {
    // code to be executed
}

In this syntax, constant name is the name to be used for a constant that will contain the current item from the collection or range through which the loop is iterating. The code in the body of the loop will typically use this constant name as a reference to the current item in the loop cycle. The collection or range references the item through which the loop is iterating. For example, this could be an array of string values, a range operator, or even a string of characters (the topic of collections will be covered in greater detail within the course section entitled “Swift Array and Dictionary Collections”).

Consider, for example, the following for-in loop construct:

C++
for index in 1...5 {
print("Value of index is \(index)")
}

The loop begins by stating that the current item is to be assigned to a constant named index. The statement then declares a closed range operator to indicate that the for-in loop is to iterate through a range of numbers, starting at 1 and ending at 5. The body of the loop simply prints out a message to the console panel indicating the current value assigned to the index constant, resulting in the following output:

Value of index is 1
Value of index is 2
Value of index is 3
Value of index is 4
Value of index is 5

As will be demonstrated in the “Swift Array and Dictionary Collections” lesson, the for-in loop is of particular benefit when working with collections, such as arrays and dictionaries.

The declaration of a constant name in which to store a reference to the current item is not mandatory. If a reference to the current item is not required in the body of the for-in loop, the constant name in the loop declaration can be replaced by an underscore character (_). For example:

C++
var count = 0
for _ in 1...5 {
// No reference to the current value is required.
count += 1
}
print("count = \(count)")

The while loop

The Swift for-in loop described previously works well when it is known in advance how many times a particular task needs to be repeated in a program. There will, however, be instances where code needs to be repeated until a certain condition is met with no way of knowing in advance how many repetitions are going to be needed to meet that criteria. To address this need, Swift provides the while loop.

Essentially, the while loop repeats a set of tasks while a specified condition is met. The while loop syntax is defined as follows:

while condition {
      // Swift statements go here
}

In the above syntax, condition is an expression that will return either true or false and the // Swift statements go here comment represents the code to be executed while the condition expression is true. For example:

C++
var myCount = 0
while myCount < 100 {
myCount += 1
}
print("myCount = \(myCount)")

In the above example, the while expression will evaluate whether the myCount variable is less than 100. If it is already greater than 100, the code in the braces is skipped and the loop exits without performing any tasks.

On the other hand, if myCount is not greater than 100, the code in the braces is executed and the loop returns to the while statement, and repeats the evaluation of myCount. This process repeats until the value of myCount is greater than 100. At which point, the loop exits.

The repeat ... while loop

The repeat … while loop replaces the do .. while loop from early versions of the Swift programming language. It is often helpful to think of the repeat ... while loop as an inverted while loop. The while loop evaluates an expression before executing the code contained in the body of the loop. If the expression evaluates to false on the first check, then the code is not executed. The repeat ... while loop, on the other hand, is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once. For example, you may want to keep stepping through the items in an array until a specific item is found. You know that you have to at least check the first item in the array to have any hope of finding the entry you need. The syntax for the repeat ... while loop is as follows:

repeat {
       // Swift statements here
} while conditional expression

In the repeat ... while example below the loop will continue until the value of a variable named i equals 0:

C++
var i = 10
repeat {
i -= 1
print("i = \(i)")
} while (i > 0)

Breaking from loops

Having created a loop, it is possible that under certain conditions you might want to break out of the loop before the completion criteria have been met (particularly if you have created an infinite loop). One such example might involve continually checking for activity on a network socket. Once the activity has been detected it will most likely be necessary to break out of the monitoring loop and perform some other task.

For the purpose of breaking out of a loop, Swift provides the break statement which breaks out of the current loop and resumes execution at the code directly after the loop. For example:

C++
var j = 10
for _ in 0 ..< 100
{
j += j
if j > 100 {
break
}
print("j = \(j)")
}

In the above example, the loop will continue to execute until the value of j exceeds 100. At this point, the loop will exit and execution will continue with the next line of code after the loop.

The continue statement

The continue statement causes all remaining code statements in a loop to be skipped and the execution to be returned to the top of the loop. In the following example, the print function is only called when the value of variable i is an even number:

C++
var i = 1
while i < 20
{
i += 1
if (i % 2) != 0 {
continue
}
print("i = \(i)")
}

The continue statement in the above example will cause the print call to be skipped unless the value of i can be divided by 2 with no remainder. If the continue statement is triggered, execution will skip to the top of the while loop, and the statements in the body of the loop will be repeated (until the value of i exceeds 19).

Lesson recap

  • Loops are sequences of Swift statements to be executed repeatedly until a condition is met.

  • The for-in loop can be used to iterate a specific number of times. This is typically over a sequence of items contained in a collection or number range.

  • The while loop is useful when you need to perform a task an indefinite number of times until a condition is met.

  • If the condition has already been met when execution reaches the while loop, none of the statements in the loop body will be executed.

  • The repeat ... while loop is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once. Unlike the while loop, the condition is only checked after the body has been executed.

  • Use the break statement to exit entirely from the current loop.

  • Use the continue statement to skip the remaining statements in the loop body, and return execution to the top of the loop.

Quiz

Complete this quiz to test your knowledge of looping syntax in Swift.

Technical Quiz
1.

Which is the best statement to use when you need to perform a task a specific number of times?

A.

A while loop

B.

A repeat ... while loop

C.

A for-in loop


1 / 3

Exercises

Put your knowledge of looping control flow in Swift to work by completing the following exercises.

Exercise 1

The following code creates an infinite loop, which will never exit. Add an if statement to exit the loop when variable i equals 10.

Exercise
Solution
var i = 0
while (true) {
i += 1
}
print("i = \(i)")

Exercise 2

Modify the following for-in loop so that the current value is output via a print statement.

Exercise
Solution
for _ in 1...5 {
}