Swift

Module 3: Swift Control Flow & Conditions Tutorial | Master If, Guard, Switch & Loops

Module 3: Control Flow & Conditions in Swift

Swift programs become powerful when you can control the flow of execution based on conditions. In this module, you’ll learn how to use conditional statements, loops, and switch cases effectively. These constructs help your program make decisions, repeat tasks, and handle different scenarios smoothly.

1. Introduction to Control Flow

Control flow statements determine the order in which your code runs. Instead of running every line sequentially, you can create branches and loops to react to data or repeat tasks.

Swift supports several control flow constructs:

  • if and else statements
  • guard statements
  • switch statements
  • Loops: for-in, while, and repeat-while

2. Conditional Statements

a. if and else

The simplest way to make decisions:

let temperature = 30

if temperature > 25 {
    print("It's a hot day!")
} else {
    print("It's a cool day!")
}

– The condition inside if must evaluate to a Bool (true or false).
– The else block runs if the if condition is false.
– You can add multiple conditions with else if.

Example:

let score = 85

if score >= 90 {
    print("Grade: A")
} else if score >= 75 {
    print("Grade: B")
} else if score >= 60 {
    print("Grade: C")
} else {
    print("Grade: F")
}

b. guard Statement

guard is used to exit early if conditions aren’t met. It’s great for validating input and improving readability.

func greet(person: String?) {
    guard let name = person else {
        print("No name provided.")
        return
    }
    print("Hello, \(name)!")
}

greet(person: "Alice") // Hello, Alice!
greet(person: nil)     // No name provided.

– If the guard condition fails, you must exit the current scope (return, break, or continue).
guard helps avoid deep nesting.

3. Switch Statement

The switch statement matches a value against multiple cases and runs the matching block.

let day = 3

switch day {
case 1:
    print("Monday")
case 2:
    print("Tuesday")
case 3:
    print("Wednesday")
default:
    print("Another day")
}

– Unlike many languages, Swift’s switch must be exhaustive (cover all possible values).
– Use default case to handle any unmatched value.
– Cases don’t fall through by default (no implicit fallthrough).

Matching Multiple Values

let letter = "a"

switch letter {
case "a", "e", "i", "o", "u":
    print("Vowel")
default:
    print("Consonant")
}

4. Loops

a. for-in Loop

Loop over sequences like arrays or ranges.

for i in 1...5 {
    print("Count: \(i)")
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Loop over arrays:

let fruits = ["Apple", "Banana", "Cherry"]

for fruit in fruits {
    print(fruit)
}

b. while Loop

Runs as long as a condition is true.

var counter = 5

while counter > 0 {
    print("Countdown: \(counter)")
    counter -= 1
}

c. repeat-while Loop

Runs the loop body once before checking the condition.

var n = 1

repeat {
    print("Number \(n)")
    n += 1
} while n <= 3

5. Control Transfer Statements

Swift provides statements to transfer control inside loops:

  • break: exits the loop immediately
  • continue: skips the current iteration and proceeds to the next

Example:

for number in 1...5 {
    if number == 3 {
        continue  // Skip 3
    }
    if number == 5 {
        break    // Stop loop at 5
    }
    print(number)
}

Output:

1
2
4

6. Using Conditions in Practice: Example Program

Let’s create a simple Swift program that takes user input (simulated), checks age eligibility, and prints a message:

// eligibility.swift

let age = 20

if age >= 18 {
    print("You are eligible to vote.")
} else {
    print("You are not eligible to vote.")
}

switch age {
case 0...12:
    print("You are a child.")
case 13...19:
    print("You are a teenager.")
case 20...59:
    print("You are an adult.")
default:
    print("You are a senior citizen.")
}

Run this using:

swift eligibility.swift

Output:

You are eligible to vote.
You are an adult.

7. Summary & Best Practices

  • Use if-else for simple branching decisions.
  • Use guard for early exits to improve readability.
  • Use switch for matching multiple discrete values.
  • Use loops (for-in, while, repeat-while) for repetition.
  • Remember Swift’s switch is exhaustive and no implicit fallthrough.
  • Use break and continue to control loop flow.

8. Practice Exercises

  1. Write a program that prints whether a number is even or odd using if-else.
  2. Use a switch to print seasons based on a month number.
  3. Create a for-in loop to sum numbers from 1 to 100.
  4. Use guard to validate a username string is not empty.
  5. Write a while loop that prints multiples of 3 up to 30.

Leave a Reply

Your email address will not be published. Required fields are marked *