Swift loop
Sometimes we may need to execute the same piece of code multiple times. In general, statements are executed sequentially: the first statement in the function executes first, then the second statement, and so on.
Programming languages provide a variety of control structures for more complex execution paths.
Loop statements allow us to execute a statement or group of statements more than once, and here's a flowchart of circular statements in most programming languages:
The type of loop
The Swift language provides the following types of loops. Click on the link to see a detailed description of each type:
The type of loop | Describe |
---|---|
Traversing all elements in a collection, such as intervals represented by numbers, elements in an array, characters in strings. | |
Used to repeat a series of statements until a specific condition is reached, typically by increasing the value of the counter after each loop completes. | |
Run a series of statements, and if the condition is true, it runs repeatedly until the condition becomes false. | |
A similar while statement differs from a block of code that executes a loop before determining the loop condition. |
Loop control statements
Loop control statements change the order in which your code is executed, allowing you to jump code. Swift has the following loop control statements:
The control statement | Describe |
---|---|
Tell a loop body to stop the loop iteration immediately and restart the next loop iteration. | |
Interrupt the current loop. | |
If you continue with the following case after a case has been executed, you need to use the fallthrough keyword. |