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 ...