The continue
statement in Swift is used to skip the current iteration of a loop and move to the next one. Unlike the break
statement, which completely exits a loop, the continue
statement allows the loop to proceed while bypassing specific iterations based on a condition. This is particularly useful when you want to ignore certain values in a loop or avoid executing specific code for a particular iteration.
In this article, we’ll explore how to use the continue
statement in Swift, look at its use in different types of loops (such as for
, while
, and repeat-while
), and discuss practical use cases for skipping iterations. We’ll also cover best practices for using continue
effectively in your code.
Using continue
in a for
Loop
In a for
loop, the continue
statement skips the current iteration and moves to the next one. When continue
is encountered, Swift ignores the remaining code in the loop body for that iteration and jumps to the next iteration.
Example 1: Skipping Even Numbers in a for
Loop
for i in 1...10 {
if i % 2 == 0 {
continue // Skip even numbers
}
print("Odd number: \(i)")
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
In this example, the continue
statement skips the even numbers (i.e., when i % 2 == 0
), so only odd numbers are printed. The loop proceeds to the next iteration whenever the condition is true.
Using continue
in a while
Loop
The continue
statement works the same way in while
loops as it does in for
loops. When continue
is encountered, Swift skips the remaining code in the loop body and reevaluates the loop’s condition for the next iteration.
Example 2: Skipping Multiples of 3 in a while
Loop
var number = 0
while number < 10 {
number += 1
if number % 3 == 0 {
continue // Skip multiples of 3
}
print("Number: \(number)")
}
Output:
Number: 1
Number: 2
Number: 4
Number: 5
Number: 7
Number: 8
Number: 10
In this example, the continue
statement skips numbers that are multiples of 3 (i.e., when number % 3 == 0
). The loop continues without printing those numbers.
Using continue
in a repeat-while
Loop
In a repeat-while
loop, the continue
statement behaves similarly to how it works in for
and while
loops. When continue
is encountered, the remaining code in the loop body is skipped, and the condition is checked again for the next iteration.
Example 3: Using continue
in a repeat-while
Loop
var count = 0
repeat {
count += 1
if count % 4 == 0 {
continue // Skip multiples of 4
}
print("Count: \(count)")
} while count < 10
Output:
Count: 1
Count: 2
Count: 3
Count: 5
Count: 6
Count: 7
Count: 9
Count: 10
In this example, the continue
statement skips numbers that are multiples of 4, and the repeat-while
loop continues with the next iteration.
Skipping Iterations in Nested Loops
The continue
statement can be used in nested loops to skip iterations in the innermost loop while allowing the outer loop to continue. Each continue
only affects the loop in which it is called.
Example 4: Skipping Iterations in a Nested Loop
for i in 1...3 {
for j in 1...3 {
if j == 2 {
continue // Skip when j equals 2
}
print("i = \(i), j = \(j)")
}
}
Output:
i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3
In this example, the continue
statement skips the iteration where j
equals 2
for each value of i
. The outer loop (i
) continues unaffected, while the inner loop (j
) skips over the iteration where j == 2
.
Practical Use Cases for continue
The continue
statement is useful in situations where you want to selectively skip certain iterations without breaking out of the loop entirely. Here are some practical use cases:
- Skipping invalid input: You can use
continue
to skip over invalid or unwanted input during iteration and continue processing the next input.
Example 5: Skipping Empty Strings in an Array
let strings = ["apple", "", "banana", "", "cherry"]
for string in strings {
if string.isEmpty {
continue // Skip empty strings
}
print("String: \(string)")
}
Output:
String: apple
String: banana
String: cherry
In this example, the continue
statement skips empty strings in the strings
array, allowing only non-empty strings to be printed.
- Skipping certain conditions in data processing: You can use
continue
to skip over data elements that don’t meet specific criteria while processing a collection.
Example 6: Skipping Low Scores in a Test
let scores = [95, 82, 43, 88, 59, 72]
for score in scores {
if score < 60 {
continue // Skip scores lower than 60
}
print("Passing score: \(score)")
}
Output:
Passing score: 95
Passing score: 82
Passing score: 88
Passing score: 72
In this example, the continue
statement skips scores that are less than 60
, printing only the passing scores.
- Skipping specific conditions in mathematical calculations: If you are performing mathematical operations in a loop, you can use
continue
to avoid calculations for certain values.
Example 7: Skipping Division by Zero
let numbers = [10, 20, 0, 40]
for number in numbers {
if number == 0 {
print("Cannot divide by zero. Skipping.")
continue // Skip division by zero
}
print("100 divided by \(number) is \(100 / number)")
}
Output:
100 divided by 10 is 10
100 divided by 20 is 5
Cannot divide by zero. Skipping.
100 divided by 40 is 2
In this example, the continue
statement prevents division by zero, ensuring that the program skips the invalid calculation and proceeds with the next number.
Combining continue
with where
in Loops
In some cases, you can achieve similar behavior to continue
by using the where
clause in a for
loop. The where
clause allows you to filter loop iterations based on a condition.
Example 8: Using where
to Skip Iterations
for i in 1...10 where i % 2 != 0 {
print("Odd number: \(i)")
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
In this example, the where
clause achieves the same result as using continue
to skip even numbers. It only processes odd numbers.
Best Practices for Using continue
- Use
continue
for selective iteration skipping: When you need to skip over specific iterations of a loop,continue
is a clean and efficient way to do so. - Avoid overusing
continue
: Usingcontinue
in multiple places within a loop can make your code harder to read. If possible, try to refactor the logic to reduce the need forcontinue
. - Use
continue
to avoid unnecessary processing: Usecontinue
to skip iterations where processing is unnecessary or invalid, improving the performance and clarity of your code. - Consider using
where
for filtering: In some cases, using thewhere
clause in afor
loop can be more concise and readable than usingcontinue
.
Conclusion
The continue
statement in Swift is a valuable tool for controlling loop behavior by skipping specific iterations while allowing the loop to continue. Whether you’re processing arrays, handling user input, or performing calculations, continue
lets you selectively bypass certain iterations based on conditions, making your loops more efficient and precise.
In this article, we covered:
- The use of
continue
infor
,while
, andrepeat-while
loops. - Skipping iterations in nested loops with
continue
. - Practical use cases for `
continue`, such as skipping empty strings or avoiding division by zero.
- Combining
continue
with thewhere
clause for filtering iterations.
In the next article, we’ll dive into the Swift guard
Statement—a powerful flow control tool that allows you to exit code early when conditions aren’t met, and how to use it for cleaner, more readable code.
Happy coding!