Swift Loops

Sometimes, we may need to execute the same block of code multiple times. In general, statements are executed sequentially: the first statement in a function executes first, then the second, and so on.

Programming languages provide various control structures for more complex execution paths.

Loop statements allow us to execute a statement or a group of statements multiple times. Below is a flowchart of loop statements in most programming languages:

循环结构

Loop Types

The Swift language provides the following loop types. Click the links to view a detailed description of each type:

Loop Type Description

for-in

Iterates over all elements in a collection, such as ranges of numbers, elements in an array, or characters in a string.

for loop

This loop method has been deprecated in Swift 3.

Used to repeatedly execute a series of statements until a specific condition is met, generally by increasing the value of a counter after each loop completes.

while loop

Runs a series of statements; if the condition is true, it repeats until the condition becomes false.

repeat...while loop

Similar to the while statement, except that the loop's code block is executed once before the loop condition is evaluated.

Loop Control Statements

Loop control statements change the execution order of your code; through them, you can implement code jumps. Swift provides the following loop control statements:

Control Statement Description

continue statement

Tells a loop body to immediately stop the current loop iteration and restart the next loop iteration.

break statement

Interrupts the current loop.

fallthrough statement

If you want to continue executing the following case after one case has finished executing, you need to use the fallthrough (penetration) keyword.
Other Extensions