Swift Tutorials: Understanding the `continue` Statement 🎯

beginner
18 min

Swift Tutorials: Understanding the continue Statement 🎯

Welcome back to CodeYourCraft! Today, we're going to delve into the Swift programming language and explore one of its control flow statements: the continue statement. This powerful tool can help you navigate loops more efficiently and write cleaner code. Let's get started! 📝

What is the continue Statement? 🤔

The continue statement is used within loops (such as for, while, and repeat-while) to skip the current iteration and move on to the next one. This can be particularly useful when you want to omit certain iterations based on specific conditions. 💡

Syntax and Usage 💡

The syntax for the continue statement is simple:

swift
for (index, element) in collection { // Code to execute for each iteration if condition { continue } // Code to execute for the next iteration (if the condition is not met) }

When you encounter the continue keyword, the current iteration is skipped, and the loop advances to the next iteration.

Example: Filtering an Array 💡

Let's consider an example where we have an array of numbers and want to filter out any numbers that are less than 10.

swift
let numbers = [1, 5, 8, 3, 12, 6, 4] for number in numbers { if number < 10 { continue } print(number) }

In this example, when the loop encounters a number less than 10, it skips the printing of that number and moves on to the next iteration. The output of this code would be:

12 12 6

Quiz 💡

Advanced Example: Nested Loops 💡

In some cases, you might need to use the continue statement in nested loops. Here's an example where we're printing all pairs of numbers from two arrays that add up to a given sum.

swift
let array1 = [1, 2, 3, 4, 5] let array2 = [6, 7, 8, 9, 10] let sum = 9 for number1 in array1 { for number2 in array2 { if number1 + number2 == sum { print("\(number1) + \(number2) = \(sum)") } else if number1 + number2 > sum { continue } } }

In this example, we're using the continue statement to skip further iterations of the inner loop once the sum exceeds the desired value. The output of this code would be:

1 + 8 = 9 2 + 7 = 9

And that's a wrap for our tutorial on the continue statement in Swift! As always, practice makes perfect. Try writing your own examples and experiment with different conditions to get a better understanding of this control flow statement.

Happy coding! 💡