Coding/Learn/swift/swift loops and control transfer
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnLoops, Defer Execution & Labeled Statements
9 / 20 0%
Lesson 09 of 20
8 mins read

Loops, Defer Execution & Labeled Statements

PreviousNext Lesson
In Plain English

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.

The Mental Model

"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.

PointCore Rules to Remember

Point star
Guaranteed Defer Cleanup: defer executes even if an error is thrown or an early return occurs.
Point star
LIFO Defer Order: Multiple defer blocks inside the same scope execute in reverse order (Last-In, First-Out).
Point star
Labeled Control: Enables breaking or continuing specific outer loops cleanly without flag variables.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Use for _ in 1...5 when you need to repeat an action N times without using the loop counter variable.

Live Interactive Example

Hit Run Code to see it live
Defer Cleanup Execution and Labeled Loops
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Output Console
Click "Run Code" to view the rendered output.
How it works: Defers executed in reverse order (2 then 1), and break outerLoop exited nested loops cleanly.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Enumerate Array Elements

  • PointDeclare let languages = ["Swift", "Go", "Rust"].
  • PointUse for (idx, lang) in languages.enumerated() to print "#\(idx + 1): \(lang)".
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates