After the branching structures if and switch, the most common structures you'll use in your programming are looping structures, which cause your program flow to execute the same code iteratively.

The looping structures you'll learn in this section are the following:

As with the switch control structure, there are many features and flexible options provided by these structures that make Swift more expressive and powerful than many other programming languages.

The following diagram illustrates how the for...in statement works:

The for…in Statement

Most programming languages have a for statement used to execute a code statement a certain number of times. The preceding diagram illustrates how the for...in statement works. A canonical example of a for loop in C, similar to many other C-inspired languages, is the following:

The equivalent for loop written in Swift is as follows:

Comparing the two for loops, they appear quite similar, but you could argue the Swift version is easier to read!

The while Loop

Where the for loop executes a code block a predetermined number of times, the while loop continues executing a code block until a Boolean expression evaluates as false. The preceding diagram illustrates how the while loop works.

The general syntax of the while loop is as follows:

The syntax rules for the while loop are essentially identical to that of the if statement, specifically the following ones:

The while statement supports the break and continue keywords to redirect flow control in the same manner as the for loop.

The following example uses a while loop to iterate over an array of Double values to calculate an average for all prices less than seven (7):

Loops and iteration are a core part of any computer program. Data is often stored in array and collection data structures, and loops allow you to develop concise, well-organized code to operate on them.

Use an Xcode playground to practice using the looping flow control structures we have covered in this section.