Python Loops, Defer Execution & Labeled Statements
Master loops and execution transfers in Swift. Learn for-in loops with tuple enumeration (.enumerated()), while, repeat-while, labeled statements for breaking outer loops, and the defer keyword for guaranteed LIFO resource cleanup.
"defer is like writing your return checklist right as you check into a hotel room ("put room key on desk"). Even if you leave in a rush, the checklist executes right as you step through the doorway."
Deep Dive: How It Works
for-in Loops: Iterates over arrays, dictionaries, sets, ranges, and characters.
Enumerated Traversal: for (index, item) in list.enumerated() yields both offset and value.
repeat-while: Executes loop body at least once before testing condition (analogous to do-while in C/Java).
The defer Keyword: Schedules a block of code to run when the current execution scope exits, regardless of how it exits.
Labeled Statements: Prefix loops with a label (outerLoop: for ...) to specify which loop break outerLoop terminates.
Syntax Blueprint
defer { print("Cleanup executed") }
for (idx, val) in items.enumerated() {
print("\(idx): \(val)")
}Use defer for guaranteed exit cleanup and .enumerated() for indexed traversal.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Expecting defer inside a loop to run when the function returns.Why it happens: defer executes at the end of the immediate enclosing scope (each loop iteration), not function scope.
How to fix: Place defer at the appropriate scope level where cleanup is intended.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Enumerate Array Elements
Declare let languages = ["Swift", "Go", "Rust"].
Use for (idx, lang) in languages.enumerated() to print "#\(idx + 1): \(lang)".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.