0
0
Swiftprogramming~10 mins

Break and continue behavior in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Break and continue behavior
Start Loop
Check Condition
Yes
Inside Loop Body
If 'continue' condition?
YesSkip rest, next iteration
If 'break' condition?
YesExit Loop
Execute remaining loop code
Next iteration
Back to Check Condition
End Loop
Back to Check Condition
The loop checks a condition each time. If 'continue' is met, it skips to the next iteration. If 'break' is met, it exits the loop immediately.
Execution Sample
Swift
for i in 1...5 {
    if i == 3 {
        continue
    }
    if i == 4 {
        break
    }
    print(i)
}
This loop prints numbers 1 to 5 but skips 3 and stops before printing 4.
Execution Table
IterationiCheck i==3ActionCheck i==4ActionPrint Output
11FalseNo continueFalseNo breakPrint 1
22FalseNo continueFalseNo breakPrint 2
33TrueContinue - skip print---
44FalseNo continueTrueBreak - exit loop-
------Loop ends
💡 Loop stops at i=4 because break condition is met.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
i-1234-
Key Moments - 3 Insights
Why does the loop skip printing when i equals 3?
Because at iteration 3, the condition i == 3 is true, so 'continue' runs, skipping the print statement as shown in execution_table row 3.
Why does the loop stop before printing 4?
At iteration 4, the condition i == 4 is true, so 'break' runs, exiting the loop immediately as shown in execution_table row 4.
Does 'continue' stop the entire loop?
No, 'continue' only skips the rest of the current iteration and moves to the next one, as seen in iteration 3 in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed when i equals 3?
ANothing
B3
C4
DError
💡 Hint
Check row 3 in the execution_table where 'continue' causes skipping print.
At which iteration does the loop stop executing?
AAfter i=2
BAt i=4
CAfter i=3
DAt i=5
💡 Hint
Look at the 'break' action in execution_table row 4.
If we remove the 'continue' statement, what will be printed?
A1, 2
B1, 2, 3, 4
C1, 2, 3
D1, 2, 4
💡 Hint
Without 'continue', i=3 will print, but loop breaks at i=4 before printing it.
Concept Snapshot
Swift 'break' exits the loop immediately.
Swift 'continue' skips the rest of current iteration.
Use 'break' to stop looping early.
Use 'continue' to skip specific steps.
Both affect loop flow control.
Full Transcript
This example shows a Swift for-loop from 1 to 5. When i equals 3, the 'continue' statement skips printing 3 and moves to the next number. When i equals 4, the 'break' statement stops the loop entirely, so 4 and 5 are not printed. The execution table tracks each iteration's checks and actions, showing how 'continue' skips printing and 'break' ends the loop. Variables are tracked to show i's value each step. Key moments clarify why skipping and stopping happen. The quiz tests understanding of these behaviors.