Swift Tutorial

Swift Data Types

Swift Control Flow

Swift Functions

Swift Collections

Swift OOPs

Swift Additional Topics

Swift - If-else Statement

The if-else statement in Swift is a fundamental control flow structure that allows code to execute based on whether a specific condition is true or false.

Syntax:

The general structure of an if-else statement is as follows:

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

Example:

Let's consider a simple example where we check if a number is even or odd:

let number = 5

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

// Output: The number is odd.

In this example:

  • The if condition checks if the remainder of the number divided by 2 is zero (meaning the number is even).
  • If the condition is true, it prints "The number is even."
  • If the condition is false (as is the case with the number 5), the code inside the else block executes, printing "The number is odd."

Notes:

  • The else block is optional. You can have an if statement without an else:
if condition {
    // Code to execute if the condition is true
}
  • Parentheses () around conditions are optional in Swift. So, both if condition {...} and if (condition) {...} are valid, but the former is more idiomatic in Swift.

  • Always ensure that the condition inside the if statement returns a boolean (true or false). If it doesn't, the Swift compiler will raise an error.

  • The if-else statement can be expanded further using else if to check for multiple conditions, which was discussed in the previous answer on the if-else-if statement.

  1. How to use if-else in Swift programming:

    • Description: The if-else statement in Swift allows you to conditionally execute code blocks based on a given condition.

    • Code:

      let number = 10
      
      if number > 0 {
          print("Number is positive")
      } else {
          print("Number is non-positive")
      }
      
  2. Conditional statements in Swift with if-else:

    • Description: if-else is a fundamental conditional statement in Swift, allowing you to handle alternative code paths.

    • Code:

      let temperature = 25
      
      if temperature > 30 {
          print("It's hot!")
      } else {
          print("It's not too hot.")
      }
      
  3. Handling multiple conditions in if-else in Swift:

    • Description: Multiple conditions can be handled using chained if-else statements.

    • Code:

      let grade = 85
      
      if grade >= 90 {
          print("A")
      } else if grade >= 80 {
          print("B")
      } else {
          print("C or below")
      }
      
  4. Nested if-else statements in Swift:

    • Description: if-else statements can be nested to handle more complex conditions.

    • Code:

      let age = 25
      
      if age >= 18 {
          print("You are an adult")
          if age >= 21 {
              print("You can buy alcohol")
          }
      } else {
          print("You are a minor")
      }
      
  5. Using logical operators in Swift if-else:

    • Description: Logical operators (&&, ||, !) can be used to combine conditions in if-else statements.

    • Code:

      let isWeekend = true
      let hasPartyInvitation = false
      
      if isWeekend || hasPartyInvitation {
          print("Let's party!")
      } else {
          print("No party today.")
      }
      
  6. Swift if-else statement with optionals:

    • Description: Optionals can be safely unwrapped using if-else statements with optional binding (if let or guard let).

    • Code:

      let optionalValue: Int? = 42
      
      if let unwrappedValue = optionalValue {
          print("Optional has a value: \(unwrappedValue)")
      } else {
          print("Optional is nil")
      }
      
  7. Conditional expressions and ternary operator in Swift:

    • Description: Ternary conditional operator (a ? b : c) provides a concise way to express if-else conditions.

    • Code:

      let isSunny = true
      
      let weatherMessage = isSunny ? "It's sunny!" : "It's not sunny."
      print(weatherMessage)