Understanding Continue Statement
The continue statement can be used in for
, while
, and repeat-while
loops. When encountered, it skips the current iteration and proceeds to the next one. This is particularly useful when filtering specific values from a dataset or when optimizing loop execution.
Example 1: Skipping Odd Numbers in an Array
The following Swift program demonstrates how to use the continue
statement to print only even numbers from an array:
import
Foundation
let numbers = [25, 18, 9, 44, 61, 32, 55, 88]
print("Even Numbers in the Array:")
for num in numbers {
if num % 2 != 0 {
continue // Skip odd numbers
}
print(num)
}
Output
18
44
32
88
Example 2: Skipping a Specific Value in an Array
This example demonstrates skipping the value -10
while iterating through an array.
import
Foundation
let values = [5, -10, 15, 20, -10, 30]
print("Filtered Values:")
for val in values {
if val == -10 {
continue // Skip -10
}
print(val)
}
Output
5
15
20
30
Example 3: Filtering Short City Names
This example filters out cities with names shorter than 6 characters.
import
Foundation
let cities = ["Tokyo", "Berlin", "London", "NY", "Paris", "Oslo"]
print("Cities with names longer than 5 characters:")
for city in cities {
if city.count < 6 {
continue // Skip short city names
}
print(city)
}
Output
Berlin
London
Paris