Swift loop


Sometimes, we may need to execute the same block of code multiple times. Normally, statements are executed sequentially: the first statement in the function is executed first, followed by 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 statement group multiple times. The following is a flow chart of loop statements in most programming languages:

1058.png

Loop type

Swift language provides the following loop types. Click on the links to view detailed descriptions of each type:

##Cycle TypeDescriptionTraverse all elements in a collection, such as intervals represented by numbers, elements in arrays, and characters in strings. is used to repeatedly execute a series of statements until a specific condition is reached, usually by incrementing the counter after each loop is completed. value to achieve. Run a series of statements. If the condition is true, it will be run repeatedly until the condition becomes false. Similar to the while statement, the difference is that the loop code block is executed once before the loop condition is judged.
for -in

for loop

while loop

repeat...while loop


Loop control statement

Loop control statement changes the execution order of your code, through which you can realize code jumps. Swift has the following loop control statements:

Control statementDescription Tells a loop body to immediately stop the current loop iteration and restart the next loop iteration. breaks the current loop. If you continue to execute the following case after a case is executed, you need to use the fallthrough keyword.
continue statement

break statement

fallthrough statement