Swift Continue

Welcome to Swift Tutorial. In this tutorial, we will learn about Swift continue keyword with the help of examples.

Swift continue is used to skip the statements after continue statement inside the loop block and continue with the rest of iterations.

Continue keyword can be used inside swift while loop, swift repeat-while loop and also swift for loop.

The main difference between swift break and swift continue is that swift break keyword breaks the loop while continue keyword skips the loop and continues with the next iteration.

Syntax – Swift continue statement

Following is syntax of continue statement in a Swift program.

 continue

In while loop

 while boolean_expression {
     // some statements
     continue
     // some other statements
 }

In for loop

 for index in var {
     // some statements
     continue
     // some other statements
 }

In repeat while loop

 while boolean_expression {
     // some statements
     continue
     // some other statements
 }

Example 1 – Swift Continue statement with While Loop

In this example, we will use continue statement in swift while loop. For some reason, consider that we would like to skip the loop when i becomes 3 and continue thereafter.

main.swift

var i = 0

while i < 6 {
   if i==3 {
        i = i + 1
       continue
   }
   print("i : \(i)")
   i = i + 1
}

print("rest of the statements")

Output

$swift while_loop_continue_example.swift
i : 0
i : 1
i : 2
i : 4
i : 5
rest of the statements

Example 2 – Swift Continue statement with For Loop

In this example, we will use continue statement in swift for loop. For some reason, consider that we would like to skip the loop when i becomes 3 and continue thereafter.

main.swift

var i = 0

for i in 1..<6 {
   if i==3 {
       continue
   }
   print("i : \(i)")
}

print("rest of the statements")

Output

$swift for_loop_continue_example.swift
i : 1
i : 2
i : 4
i : 5
rest of the statements

Example 3 – Swift Continue statement with Repeat While Loop

In this example, we will use continue statement in swift repeat while loop. For some reason, consider that we would like to skip the loop when i becomes 3 and continue thereafter.

main.swift

var i = 0

repeat {
   if i==3 {
       i = i + 1
       continue
   }
   print("i : \(i)")
   i = i + 1
} while i<5

print("rest of the statements")

Output

$swift repeat_while_loop_break_example.swift
i : 0
i : 1
i : 2
i : 4
rest of the statements

Conclusion

In this Swift Tutorial, we have learned about Swift continue statement with syntax and examples covering different scenarios.