What is Swift loop?
Basically, Loop is the specific block/segment of codes that let you repeat it. As a result, thanks to this Swift Loop, you don’t need to write the same thing many times. In addition, the flowchart below illustrates how loop statements work:
Types of Swift loop
For in loops
For in loops is perhap the Swift loop’s most well-known . Because of building -in “index”, this loop swift makes browsing data quick and simple. Therefore, the general form of a For in loop looks like:
As you can see above, the code is much clearer. From the start, we didn’t need to declare i. Then, instead of incrementing i (i+=1), for in loops already did it for us by using a set of values from 1 to 9 [1,2,3,4,5,6,7,8,9].
A for loop is the control structure that allows you to set the time of repeat structure. The following shows how the for loop works:
Here is the syntax of this kind loop swift:
- initialization: Executed first and only once
- condition: If it is true, the block inside for is executed. If it is false, the loop will end.
- increment: After the block inside the loop is executed, the increment expression is executed to update the conditional expression. Condition will now be redefined and if it is true, the block inside the loop is executed. If it is wrong, the loop ends.
Repeat – While Loops
Unlike the loop for, the condition in a repeat while loop is checked at the end of the loop. As a result, that means the block inside the repeats … while loop executed at least once. Besides that, the syntax of Repeat – While Loops as you see below:
As you see, it ran the code at least once rather than ignoring it, which may be very helpful in case you need to show at least one result rather than none.
While loop is one of the common and basic loops. A while loop performs a set of statements until a condition becomes false. The syntax of this swift loop is as follows:
Loop Control Statements
In Swift, the continue statement instructs the loop to stop what it is doing and restart at the beginning of the next iteration through the loop.
For example: Displaying odd numbers from 1 to 19
When we run the above program using the playground, we will receive the result:
The break statement used to encounter inside a loop. The loop is terminated immediately, and program control returns to the next statement following the loop.
We will receive the result: