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:
Loop type
Swift language provides the following loop types. Click on the links to view detailed descriptions of each type:
Description | |
---|---|
for -in | Traverse all elements in a collection, such as intervals represented by numbers, elements in arrays, and characters in strings.|
for loop | 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.|
while loop | Run a series of statements. If the condition is true, it will be run repeatedly until the condition becomes false.|
repeat...while loop | Similar to the while statement, the difference is that the loop code block is executed once before the loop condition is judged.
Loop control statementLoop control statement changes the execution order of your code, through which you can realize code jumps. Swift has the following loop control statements:
Description | |
---|---|
continue statement | Tells a loop body to immediately stop the current loop iteration and restart the next loop iteration.|
break statement | breaks the current loop.|
fallthrough statement | If you continue to execute the following case after a case is executed, you need to use the fallthrough keyword.