Swift

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

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 *