Menu
Coddy logo textTech

If - Else

Part of the Fundamentals section of Coddy's Swift journey — lesson 27 of 86.

Sometimes you need your program to do one thing when a condition is true and something different when it's false. The else clause provides an alternative path of execution.

let temperature = 15

if temperature > 25 {
    print("It's warm outside")
} else {
    print("It's cool outside")
}

When the condition is false, the code inside the else block runs instead. This guarantees that exactly one of the two code blocks will always execute.

For situations with more than two possibilities, you can chain multiple conditions using else if:

let score = 75

if score >= 90 {
    print("Excellent")
} else if score >= 70 {
    print("Good")
} else if score >= 50 {
    print("Pass")
} else {
    print("Fail")
}

Swift evaluates each condition from top to bottom and executes the first block where the condition is true. The final else acts as a catch-all for any remaining cases. This structure lets you handle multiple distinct scenarios in a clear, readable way.

challenge icon

Challenge

Easy
Write a function getAgeGroup that takes age and returns the corresponding age group category.

Use if, else if, and else to categorize the age into one of four groups.

Conditions:

  • If age is less than 13, return "Child"
  • If age is at least 13 but less than 20, return "Teenager"
  • If age is at least 20 but less than 65, return "Adult"
  • If age is 65 or older, return "Senior"

Parameters:

  • age (Int): The person's age

Returns: The age group category as a String

Cheat sheet

The else clause provides an alternative path when a condition is false:

if temperature > 25 {
    print("It's warm outside")
} else {
    print("It's cool outside")
}

For multiple conditions, chain them using else if:

if score >= 90 {
    print("Excellent")
} else if score >= 70 {
    print("Good")
} else if score >= 50 {
    print("Pass")
} else {
    print("Fail")
}

Swift evaluates conditions from top to bottom and executes the first block where the condition is true. The final else catches any remaining cases.

Try it yourself

func getAgeGroup(age: Int) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals