Swift - Loops



Swift Loops

A loop statement allows us to execute a statement or group of statements multiple times. They execute in a sequential manner like the first statement in a function is executed first, followed by the second, and so on. A loop can run infinite times until the given condition is false.

For example, we want to print a series of numbers from 1 to 10. So to print the sequence we can specify 1…10 range in the for-in loop and the loop ends when it encounters 10. Following is the general form of a loop statement in most programming languages −

Loops
Loop Name Description
for-in Iterates through each element of the given sequence or collection such as array, ranges, etc. and can perform operation on them if needed.
while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
repeat...while loop Like a while statement, except that it tests the condition at the end of the loop body.

Swift programming language provides the following kinds of loops to handle looping requirements.

Example

Swift program to demonstrate the use of break statement in a for-in loop.

import Foundation

print("Numbers:")
for x in 1...5 {
   if x == 3 {    
      // When x is equal to 3 the loop will terminate
      break
   }
   print(x)
}

Output

It will produce the following output −

Numbers:
1
2

Swift - Loop Control Statements

Loop control statements allow the developer to change the execution of loops from its normal sequence. They are designed to transfer controls from one block of statements to another. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Swift supports the following control statements −

Control Statement Description
continue statement This statement tells a loop to terminate what it is doing and start again at the beginning of the next iteration through the loop.
break statement Terminates the loop statement and transfers execution to the statement immediately following the loop.
fallthrough statement The fall through statement simulates the behavior of Swift 4 switch to C-style switch.

Example

Swift program to demonstrate the use of break statement in a for-in loop.

import Foundation
print("Numbers:")
for y in 1...8 {
   if y == 5 {
    
      // When y is equal to 5 the loop will terminate
      break
   }
   print(y)
}
print("Hello Swift")

Output

It will produce the following output −

Numbers:
1
2
3
4
Hello Swift
Advertisements