Control flow redirection (break, continue) - Swift Tutorial
In Swift, control flow redirection is achieved using the break
and continue
statements. Let's take a look at how they work in different contexts:
1.break
statement:
break
is used to terminate a loop or switch statement prematurely.- In a loop, when
break
is encountered, the loop is immediately terminated, and the program execution continues after the loop. - In a switch statement,
break
is used to exit the switch block once a matching case is found. Withoutbreak
, the program execution would continue to the next case.
Example of using break
in a loop:
for number in 1...10 {
if number == 5 {
break
}
print(number)
} // Output: 1 2 3 4
Example of using break
in a switch statement:
let number = 3
switch number {
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
break
default:
print("Other")
} // Output: Three
2.continue
statement:
continue
is used to skip the remaining code in the current iteration of a loop and move to the next iteration.- When
continue
is encountered, the loop increments or updates its control variable and starts the next iteration.
Example of using continue
in a loop:
for number in 1...10 {
if number % 2 == 0 {
continue
}
print(number)
}
// Output: 1 3 5 7 9
Both break
and continue
are powerful control flow statements that help in altering the flow of execution within loops and switch statements.
If you’re interested in learning more about Swift, I recommend checking out my articles on Medium. You can access them through the template I created on Notion, which provides a structured learning process and easy navigation to different topics. Happy learning, and best of luck on your Swift programming journey!