Swift Continue Statement

In Swift, the continue statement is used to skip the current iteration of a loop and move on to the next one. It is often used in conjunction with conditional statements to selectively skip certain loop iterations.

The continue statement is particularly useful when iterating through arrays or other collections, allowing you to quickly filter out elements that do not meet certain criteria.

Syntax of the Continue Statement

The syntax of the continue statement is as follows:

1continue

When the continue statement is encountered within a loop, it immediately stops processing the current iteration of the loop and jumps to the next iteration. If the loop has no more iterations, the loop terminates.

Example 1: Skipping Even Numbers

In this example, we will use the continue statement to skip over even numbers in an array and print out only the odd numbers.

1let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 2 3for number in numbers { 4 if number % 2 == 0 { 5 continue 6 } 7 print(number) 8}

Output:

11 23 35 47 59

As you can see, the continue statement allowed us to skip over the even numbers in the array and print out only the odd numbers.

Example 2: Skipping Elements that Don't Meet a Condition

In this example, we will use the continue statement to skip over elements in an array that do not meet a certain condition.

1let names = ["William", "Jane", "Steve", "Max", "Bob", "Rachel"] 2 3for name in names { 4 if name.count < 5 { 5 continue 6 } 7 print(name) 8}

Output:

1Steve 2Max 3Rachel

As you can see, the continue statement allowed us to skip over the names that had a length of less than 5 characters and print out only the names that met the condition.

The continue statement is a useful tool for selectively skipping loop iterations based on certain conditions. It can be particularly helpful when working with collections like arrays and dictionaries, allowing you to quickly filter out elements that do not meet certain criteria.