Swift Loop Statements

Swift Loop statements are used to execute a set of statements repeatedly based on a condition or for each element in a collection. Swift provides following looping statements.

These looping statements can be controlled to break out or skip for an iteration using the following statements. These are called Loop Control Statements.

For Loop

In the following example, we use for loop to iterate over the elements of an array.

main.swift

var nums:[Int] = [ 2, 4, 6, 8 ]
 
for x in nums {
   print( x )
}

Output

2
4
6
8
Program ended with exit code: 0

While Loop

In the following example, we use while loop to execute a set of statements 5 times in a loop.

main.swift

var i = 1
 
while i <= 5 {
   print("\(i) Hello World")
   i = i + 1
}

Output

1 Hello World
2 Hello World
3 Hello World
4 Hello World
5 Hello World
Program ended with exit code: 0

Repeat While Loop

In the following example, we use repeat while loop to execute a set of statements while the value of i is less than five.

main.swift

var i = 1
 
repeat {
   print("\(i) Hello World")
   i = i + 1
} while( i < 5 )

Output

1 Hello World
2 Hello World
3 Hello World
4 Hello World
Program ended with exit code: 0

Break Statement

Break statement is used to exit a loop. In the following example, we exit for loop when the element is 6.

main.swift

var nums:[Int] = [ 2, 4, 6, 8 ]
 
for x in nums {
    if x == 6 {
        break
    }
   print( x )
}

Output

2
4
Program ended with exit code: 0

Continue Statement

Continue statement is used to skip that iteration of a loop and continue with next iterations. In the following example, we continue with next iterations of for loop when the element is 6.

main.swift

var nums:[Int] = [ 2, 4, 6, 8 ]
 
for x in nums {
    if x == 6 {
        continue
    }
   print( x )
}

Output

2
4
8
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we have learned about Swift Loops and Loop Control statements with the help of examples.