Conditional statements are fundamental in programming as they allow you to execute different code based on certain conditions. In Swift, the primary conditional statements are if, else if, else, and guard. This section will cover these statements in detail, providing examples and exercises to help you understand their usage.

  1. if Statement

The if statement is used to execute a block of code if a specified condition is true.

Syntax

if condition {
    // Code to execute if the condition is true
}

Example

let temperature = 30

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

In this example, the message "It's a hot day!" will be printed because the condition temperature > 25 is true.

  1. else Statement

The else statement is used to execute a block of code if the condition in the if statement is false.

Syntax

if condition {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Example

let temperature = 20

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

In this example, the message "It's not a hot day." will be printed because the condition temperature > 25 is false.

  1. else if Statement

The else if statement is used to specify a new condition if the first condition is false.

Syntax

if condition1 {
    // Code to execute if condition1 is true
} else if condition2 {
    // Code to execute if condition2 is true
} else {
    // Code to execute if both conditions are false
}

Example

let temperature = 15

if temperature > 25 {
    print("It's a hot day!")
} else if temperature > 15 {
    print("It's a warm day.")
} else {
    print("It's a cold day.")
}

In this example, the message "It's a cold day." will be printed because both conditions temperature > 25 and temperature > 15 are false.

  1. guard Statement

The guard statement is used to transfer program control out of a scope if one or more conditions aren’t met. It is often used for early exits in functions.

Syntax

guard condition else {
    // Code to execute if the condition is false
    return
}

Example

func checkTemperature(_ temperature: Int) {
    guard temperature > 0 else {
        print("Temperature must be above 0.")
        return
    }
    print("Temperature is valid.")
}

checkTemperature(-5)  // Output: Temperature must be above 0.
checkTemperature(10)  // Output: Temperature is valid.

In this example, the guard statement checks if the temperature is above 0. If not, it prints an error message and exits the function.

Practical Exercises

Exercise 1: Simple if Statement

Write a Swift program that checks if a number is positive and prints "The number is positive."

Solution

let number = 10

if number > 0 {
    print("The number is positive.")
}

Exercise 2: if-else Statement

Write a Swift program that checks if a number is even or odd and prints the appropriate message.

Solution

let number = 7

if number % 2 == 0 {
    print("The number is even.")
} else {
    print("The number is odd.")
}

Exercise 3: else if Statement

Write a Swift program that checks the grade of a student and prints "Excellent" for grades above 90, "Good" for grades between 70 and 90, and "Needs Improvement" for grades below 70.

Solution

let grade = 85

if grade > 90 {
    print("Excellent")
} else if grade > 70 {
    print("Good")
} else {
    print("Needs Improvement")
}

Exercise 4: guard Statement

Write a Swift function that takes an age as input and prints "Valid age" if the age is 18 or above, otherwise prints "Invalid age" and exits the function.

Solution

func checkAge(_ age: Int) {
    guard age >= 18 else {
        print("Invalid age")
        return
    }
    print("Valid age")
}

checkAge(16)  // Output: Invalid age
checkAge(20)  // Output: Valid age

Common Mistakes and Tips

  • Common Mistake: Forgetting to use curly braces {} for the code blocks in if, else if, and else statements.
    • Tip: Always use curly braces, even for single-line statements, to avoid errors and improve code readability.
  • Common Mistake: Using guard without an early exit.
    • Tip: Ensure that guard statements always include an early exit like return, break, continue, or throw.

Conclusion

In this section, you learned about the different types of conditional statements in Swift, including if, else, else if, and guard. These statements allow you to control the flow of your program based on specific conditions. Practice using these statements in various scenarios to become more comfortable with their syntax and usage. In the next section, we will explore loops, which allow you to execute a block of code multiple times.

© Copyright 2024. All rights reserved