Module 9: Control Flow in Swift – If, Switch & Loops Explained

Module 9: Control Flow in Swift – If, Switch & Loops Explained

AI Reading

Quick summary of this article

This module explains how control flow in Swift decides the order in which code runs. It covers conditional statements like if and switch, loops such as for-in, while, and repeat-while, and control transfer statements that change how loops and switch cases execute.

  • Use if statements to run code when a condition is true, with optional else if and else branches.
  • Use switch statements to match a value against multiple cases, including multiple values in one case and a default case.
  • Use for-in, while, and repeat-while loops to run code repeatedly.
  • Use break to exit a loop or switch case early, continue to skip the current loop iteration, and fallthrough to move to the next switch case.

Module 9: Control Flow in Swift

Control flow statements allow you to dictate the order in which your code executes. Swift offers powerful tools such as conditional statements and loops to manage the flow of your programs efficiently.

Conditional Statements

If Statement: Executes code when a condition is true.

let temperature = 25

if temperature > 30 {
    print("It's hot outside.")
} else if temperature > 20 {
    print("It's warm outside.")
} else {
    print("It's cold outside.")
}

Switch Statement

Switch cases check a value against multiple possible matches.

let day = "Tuesday"

switch day {
case "Monday":
    print("Start of the work week.")
case "Friday":
    print("Almost weekend!")
case "Saturday", "Sunday":
    print("Weekend!")
default:
    print("Midweek day.")
}

Loops

Loops let you execute code repeatedly.

For-In Loop

for number in 1...5 {
    print("Number is \(number)")
}

While Loop

var count = 1
while count <= 5 {
    print("Count is \(count)")
    count += 1
}

Repeat-While Loop

var counter = 1
repeat {
    print("Counter is \(counter)")
    counter += 1
} while counter <= 5

Control Transfer Statements

  • break – Exit a loop or switch case early.
  • continue – Skip the current iteration of a loop.
  • fallthrough – Continue execution to the next switch case.

Summary

  • Use if and switch for conditional logic.
  • Use for-in, while, and repeat-while loops for iteration.
  • Control transfer statements help manage loop and switch execution.

Leave a Reply

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