swift
  1. swift-nested-if-else-statement

Swift Nested if-else Statement

In Swift, a nested if-else statement is used when there are multiple conditions that need to be checked. The nested if-else statement is simply an if-else statement inside another if-else statement. This allows for more complex conditions to be evaluated.

Syntax

The syntax for a nested if-else statement in Swift is as follows:

if condition {
    // code to execute if condition is true
    if condition2 {
        // code to execute if condition2 is true
    } else {
        // code to execute if condition2 is false
    }
} else {
    // code to execute if condition is false
}

Example

Here is an example of a nested if-else statement in Swift:

let num = 10

if num >= 0 {
    if num == 0 {
        print("The number is zero")
    } else {
        print("The number is positive")
    }
} else {
    print("The number is negative")
}

Output

The output of the above code will be:

The number is positive

Explanation

The code above first checks if the variable num is greater than or equal to 0. If it is, then it checks to see if num is equal to 0. If it is, then it prints "The number is zero". If num is not equal to 0, then it prints "The number is positive". If num is less than 0, then it prints "The number is negative".

Use

The nested if-else statement is used when you need to check multiple conditions that are interdependent. This can help you write more complex logic while keeping the code readable and maintainable.

Important Points

  • A nested if-else statement is simply an if-else statement inside another if-else statement.
  • The nested if-else statement is used when multiple conditions need to be checked.
  • The conditions are evaluated in a hierarchical order.
  • The code inside each block is executed only if the associated condition is true.

Summary

A nested if-else statement in Swift is used to check multiple conditions that are interdependent. The nested nature of this statement allows for more complex logic to be evaluated. It is commonly used in Swift programming to write more readable and maintainable code.

Published on: