Swift Loops

This chapter delves into swift-loops , a fundamental feature that enables repetitive execution of code. Loops are essential for processing collections, automating tasks, and handling repetitive logic efficiently.

Chapter Goals

  • Understand the purpose and types of loops in Swift.
  • Learn how to implement different kinds of loops.
  • Explore practical applications of loops.
  • Master control statements to manage loop execution effectively.

Key Characteristics of Swift Loops

  • Iteration Over Collections: Efficiently traverse arrays, dictionaries, ranges, and sequences.
  • Condition-Based Execution: Repeat code blocks while a condition remains true.
  • Control Flexibility: Includes break, continue, and return for precise control.
  • Readable and Intuitive: Promotes clear and maintainable code.

Basic Rules for Loops

  • Ensure termination conditions to avoid infinite loops.
  • Choose the appropriate loop type based on the task.
  • Use control statements judiciously to manage execution flow.

Syntax Table

Serial No Feature Syntax/Example Description
1 For-In Loop for item in collection { … } Iterates over items in a collection or range.
2 While Loop while condition { … } Repeats code block while the condition is true.
3 Repeat-While Loop repeat { … } while condition Executes code block at least once, then checks the condition.
4 Break Statement break Exits the current loop immediately.
5 Continue Statement continue Skips the current iteration and moves to the next.

Syntax Explanation

1. For-In Loop

What is a For-In Loop?

The for-in loop iterates over a collection, range, or sequence.

Syntax

for item in collection {

    // Code to execute for each item

}

Detailed Explanation

  • Processes each element in a collection (e.g., array, dictionary, range).
  • Accesses the current element during each iteration.
  • Simplifies iteration tasks, such as summing numbers or printing elements.
  • Supports use with the enumerated() method to include indices.

Example

let numbers = [1, 2, 3, 4]

for number in numbers {

    print(number)

}

Example Explanation

  • Iterates over the numbers array.
  • Prints each number sequentially.
  • Demonstrates basic iteration through an array.

2. While Loop

What is a While Loop?

The while loop executes a block of code repeatedly as long as the condition remains true.

Syntax

while condition {

    // Code to execute while the condition is true

}

Detailed Explanation

  • The condition is evaluated before each iteration.
  • If the condition evaluates to false, the loop terminates.
  • Useful for tasks where the number of iterations is not predetermined.
  • Requires careful handling of the condition to avoid infinite loops.

Example

var count = 3

while count > 0 {

    print(“Count: \(count)”)

    count -= 1

}

Example Explanation

  • Initializes count to 3.
  • Decrements count with each iteration and prints its value.
  • Stops when count reaches 0.

3. Repeat-While Loop

What is a Repeat-While Loop?

The repeat-while loop executes a block of code at least once, then checks the condition.

Syntax

repeat {

    // Code to execute

} while condition

Detailed Explanation

  • Executes the code block before evaluating the condition.
  • Ensures the code runs at least once, even if the condition is initially false.
  • Useful for scenarios where an initial action must precede condition evaluation.

Example

var number = 0

repeat {

    print(“Number: \(number)”)

    number += 1

} while number < 3

Example Explanation

  • Prints number starting from 0.
  • Increments number in each iteration.
  • Stops when number reaches 3.

4. Break Statement

What is a Break Statement?

The break statement exits the current loop immediately, bypassing the remaining iterations.

Syntax

break

Detailed Explanation

  • Terminates the loop and resumes execution after it.
  • Commonly used to exit early based on a condition.
  • Improves efficiency by avoiding unnecessary iterations.

Example

for i in 1…5 {

    if i == 3 {

        break

    }

    print(i)

}

Example Explanation

  • Stops the loop when i equals 3.
  • Prints 1 and 2 before exiting.
  • Demonstrates controlled termination of a loop.

5. Continue Statement

What is a Continue Statement?

The continue statement skips the remaining code in the current iteration and proceeds to the next.

Syntax

continue

Detailed Explanation

  • Skips over specific iterations based on a condition.
  • Ensures the loop continues processing remaining elements.
  • Useful for ignoring unwanted conditions during iteration.

Example

for i in 1…5 {

    if i % 2 == 0 {

        continue

    }

    print(i)

}

Example Explanation

  • Skips even numbers.
  • Prints only odd numbers between 1 and 5.
  • Demonstrates selective iteration.

Real-Life Project: Multiplication Table Generator

Project Goal

Create a program to generate and display multiplication tables using loops.

Code for This Project

let number = 5

let range = 1...10




print("Multiplication Table for \(number):")

for multiplier in range {

    let result = number * multiplier

    print("\(number) x \(multiplier) = \(result)")

}

Steps

  1. Define a number for the multiplication table.
  2. Use a for-in loop to iterate through the range of multipliers.
  3. Calculate and display the result in each iteration.

Save and Run

Steps to Save and Run

  1. Write the code in your Swift IDE (e.g., Xcode).
  2. Save the file using Command + S (Mac) or the appropriate save command.
  3. Click “Run” or press Command + R to execute the program.

Benefits

  • Demonstrates practical use of loops.
  • Validates calculations dynamically.
  • Provides interactive output for user-defined numbers.

Best Practices

Why Use Loops?

  • Automate repetitive tasks efficiently.
  • Reduce code duplication and improve maintainability.
  • Enable dynamic processing of collections and ranges.

Key Recommendations

  • Choose the appropriate loop type based on the task.
  • Avoid infinite loops unless intentional and controlled.
  • Use break and continue sparingly for readability.

Example of Best Practices

let scores = [95, 82, 74]

for score in scores {

    if score < 80 {

        continue

    }

    print(“Passed with score: \(score)”)

}

Insights

Swift loops provide powerful constructs for repetitive tasks, enhancing efficiency and reducing redundancy. With a clear understanding of loops and control statements, developers can write concise and effective code.

Key Takeaways

  • Loops automate repetitive tasks and traverse collections efficiently.
  • Use for-in for collections and while/repeat-while for condition-based iteration.
  • Control statements like break and continue refine loop behavior.