Swift Control Flow

This chapter delves into swift-control-flow , a fundamental concept for directing the execution of code based on conditions and iterations. Swift provides a variety of control flow statements, such as conditionals, loops, and control transfer statements, to create dynamic and flexible programs.

Chapter Goals

  • Understand the purpose and functionality of control flow statements in Swift.
  • Learn how to use conditionals for decision-making.
  • Explore loops for repetitive tasks.
  • Implement control transfer statements for advanced flow control.

Key Characteristics of Swift Control Flow

  • Type-Safe: Ensures conditions and loop expressions are type-checked.
  • Flexible: Supports multiple conditional and looping constructs.
  • Structured: Promotes readability and maintainability through clear syntax.

Basic Rules for Control Flow

  • Conditions must evaluate to a Boolean (true or false).
  • Loops iterate over ranges, collections, or custom conditions.
  • Control transfer statements manage program flow precisely.

Syntax Table

Serial No Feature Syntax/Example Description
1 If Statement if condition { … } Executes code block if the condition is true.
2 If-Else Statement if condition { … } else { … } Executes one of two code blocks based on the condition.
3 Switch Statement switch value { case …: … } Selects code block based on matching cases.
4 For-In Loop for item in collection { … } Iterates over items in a collection or range.
5 While Loop while condition { … } Repeats code block while the condition is true.
6 Repeat-While Loop repeat { … } while condition Executes code block at least once, then checks the condition.
7 Break Statement break Exits the current loop or switch statement.
8 Continue Statement continue Skips the current iteration and moves to the next.

Syntax Explanation

1. If Statement

What is an If Statement?

The if statement evaluates a condition and executes a block of code if the condition is true.

Syntax

if condition {

    // Code to execute if condition is true

}

Detailed Explanation

  • The condition must evaluate to a Boolean value (true or false).
  • The code block is executed only if the condition is true.
  • Commonly used for decision-making where a single condition dictates the flow.
  • Supports nesting for handling multiple layers of logic.

Example

let age = 18

if age >= 18 {

    print(“You are eligible to vote.”)

}

Example Explanation

  • Checks if age is greater than or equal to 18.
  • Prints the message if the condition is true.
  • Demonstrates a simple decision-making structure.

2. If-Else Statement

What is an If-Else Statement?

The if-else statement provides two possible code paths based on the condition.

Syntax

if condition {

    // Code if condition is true

} else {

    // Code if condition is false

}

Detailed Explanation

  • Executes one block of code if the condition is true and another if it is false.
  • Useful for binary decision-making where both outcomes need handling.
  • Supports else if for chaining multiple conditions.

Example

let temperature = 15

if temperature > 20 {

    print(“It’s warm.”)

} else {

    print(“It’s cold.”)

}

Example Explanation

  • Checks if temperature is greater than 20.
  • Prints a message based on the condition’s truth value.
  • Shows how to handle alternative scenarios.

3. Switch Statement

What is a Switch Statement?

The switch statement evaluates a value and executes the matching case block.

Syntax

switch value {

case pattern1:

    // Code for pattern1

case pattern2:

    // Code for pattern2

default:

    // Code if no cases match

}

Detailed Explanation

  • Matches the value against defined patterns.
  • The default case handles unmatched values.
  • No implicit fallthrough between cases; each case must explicitly continue to the next if desired.
  • Can match multiple patterns in a single case.

Example

let day = “Monday”

switch day {

case “Monday”:

    print(“Start of the workweek.”)

case “Friday”:

    print(“End of the workweek.”)

default:

    print(“It’s a regular day.”)

}

Example Explanation

  • Evaluates the day variable and prints a message based on the matching case.
  • Demonstrates structured handling of multiple conditions.

4. 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 for each item

}

Detailed Explanation

  • Iterates over arrays, dictionaries, ranges, or custom sequences.
  • Provides access to each element during the iteration.
  • Efficient for processing collections and generating repetitive outputs.
  • Supports index-based iteration when combined with enumerated collections.

Example

let numbers = [1, 2, 3]

for number in numbers {

    print(number)

}

Example Explanation

  • Iterates over the numbers array.
  • Prints each number in the array.
  • Highlights how collections are processed element by element.

5. While Loop

What is a While Loop?

The while loop repeats a block of code while the condition is true.

Syntax

while condition {

    // Code to execute while condition is true

}

Detailed Explanation

  • The condition is evaluated before each iteration.
  • If the condition is false, the loop terminates.
  • Ideal for scenarios where the number of iterations is not known beforehand.
  • Requires careful handling to avoid infinite loops.

Example

var count = 5

while count > 0 {

    print(count)

    count -= 1

}

Example Explanation

  • Decrements count until it reaches 0.
  • Prints the countdown.
  • Demonstrates controlled iteration based on a condition.

6. Repeat-While Loop

What is a Repeat-While Loop?

The repeat-while loop executes a block of code at least once before evaluating the condition.

Syntax

repeat {

    // Code to execute

} while condition

Detailed Explanation

  • Executes the code block before checking the condition.
  • Ensures the code runs at least once.
  • Suitable for scenarios where the condition depends on prior execution.

Example

var number = 1

repeat {

    print(number)

    number += 1

} while number <= 5

Example Explanation

  • Prints numbers from 1 to 5.
  • Runs at least once, even if the condition is false initially.
  • Highlights guaranteed execution.

7. Break Statement

What is a Break Statement?

The break statement exits the current loop or switch statement immediately.

Syntax

break

Detailed Explanation

  • Terminates the loop or switch statement.
  • Commonly used to exit early based on a condition.
  • Enhances efficiency by stopping 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 loops.

8. Continue Statement

What is a Continue Statement?

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

Syntax

continue

Detailed Explanation

  • Skips the remaining code in the current iteration.
  • Useful for ignoring specific conditions during iteration.
  • Ensures the loop continues processing remaining elements.

Example

for i in 1…5 {

    if i % 2 == 0 {

        continue

    }

    print(i)

}

Example Explanation

  • Skips even numbers and prints only odd numbers.
  • Highlights selective processing during iteration.

Real-Life Project: Number Guessing Game

Project Goal

Develop a number guessing game using control flow statements.

Code for This Project

import Foundation




let targetNumber = Int.random(in: 1...100)

var attempts = 0

var guessedNumber: Int? = nil




print("Guess a number between 1 and 100:")




repeat {

    if let input = readLine(), let guess = Int(input) {

        attempts += 1

        guessedNumber = guess




        if guess < targetNumber {

            print("Too low! Try again.")

        } else if guess > targetNumber {

            print("Too high! Try again.")

        } else {

            print("Correct! You guessed it in \(attempts) attempts.")

        }

    } else {

        print("Invalid input. Please enter a number.")

    }

} while guessedNumber != targetNumber

Steps

  1. Generate a random target number.
  2. Use a repeat-while loop to allow multiple guesses.
  3. Use conditionals to guide the user toward the correct guess.
  4. Provide feedback for each guess and track attempts.

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 the use of loops, conditionals, and control statements.
  • Provides interactive feedback based on user input.
  • Encourages safe and robust input handling.

Best Practices

Why Use Control Flow?

  • Directs program execution based on conditions.
  • Simplifies repetitive tasks through loops.
  • Enhances readability and maintainability of