Skip to content
Prepare to Grow

Swift Fundamentals

Loops

Repeat work safely with for-in, ranges, while, and clear exit conditions.

Beginner4 min read2 guided activities

Before you begin

What you will understand

  • Iterate over collections and ranges.
  • Choose between for-in and while.
  • Use break and continue deliberately.
  • Avoid off-by-one and non-terminating loops.
01

Learning stage

Concept Explanation

Loops repeat a block of code. for-in is the usual choice when iterating over a sequence such as an array, range, dictionary, or string.

while repeats while a condition remains true. repeat-while performs its body once before checking the condition. break exits a loop and continue advances to its next iteration.

  • 0..<count excludes count.
  • 1...3 includes both endpoints.
  • enumerated() provides index-value pairs.
  • Dictionary iteration order should not be treated as a business rule.
02

Learning stage

Syntax & Examples

The loop enumerates lessons, skips locked items, and stops after the first incomplete available lesson.

LessonLoop.swiftswift
let lessons = ["Types", "Control Flow", "Functions"]
let locked = Set(["Functions"])

for (index, lesson) in lessons.enumerated() {
  if locked.contains(lesson) {
      continue
  }

  print("\(index + 1). \(lesson)")
}

for number in 1...3 {
  print("Attempt \(number)")
}
The locked lesson is skipped; the range prints attempts 1, 2, and 3.
03

Learning stage

Real-World Usage

These concepts appear throughout production iOS code. Focus on the requirement each technique communicates.

  • Render or transform repeated model values.
  • Search until a matching element is found.
  • Retry bounded work while a valid condition remains true.
04

Learning stage

Common Mistakes

Notice these mistakes early so the compiler and type system can help instead of becoming obstacles.

  • Using a closed range when the upper boundary should be excluded.
  • Mutating a collection in unsafe ways while iterating over it.
  • Writing a while loop whose condition never changes.
  • Using indices when direct element iteration would be clearer and safer.
05

Learning stage

Practice Exercises

Work through these activities in a small Xcode project. No embedded playground is required on this site.

Activity 1

Accumulate a total

Loop through [12, 8, 15, 5] and calculate the total without using reduce.

Hint: Declare the running total with var before the loop.

Activity 2

Skip invalid values

Print only positive numbers from a mixed array by using continue for zero and negative values.

Hint: Reject the values you don't want near the top of the loop.

06

Learning stage

Knowledge Check

Answer each question before revealing the explanation.

QUESTION 1

Which range contains 0, 1, and 2 but not 3?

  1. A.0...3
  2. B.0..<3
  3. C.1...3
  4. D.1..<3
Reveal answer

0..<3

The half-open range operator excludes its upper bound.

QUESTION 2

What does continue do inside a loop?

Reveal answer

It skips the rest of the current iteration and proceeds with the next one.

07

Learning stage

Interview Preparation

Explain the idea in terms of its purpose, behavior, and tradeoffs rather than reciting syntax.

When should you use for-in instead of while?

Short answer: Use for-in when iterating over a known sequence; use while when repetition depends primarily on a changing condition.

Explore the detailed answer

for-in communicates bounded sequence traversal and manages iteration for you. while is appropriate when the number of iterations is not known in advance, but its exit condition must be designed carefully.

Possible follow-ups

  • • What is an off-by-one error?
  • • How do break and continue differ?
08

Learning stage

Key Takeaways

Use the highest-level loop that expresses the work. Prefer direct sequence iteration, make boundaries explicit, and ensure condition-driven loops can terminate.

  • for-in is the default for sequences.
  • Half-open ranges are common for zero-based counts.
  • break exits and continue skips one iteration.
  • Every while loop needs a reachable stopping condition.