Swift Tutorial

Swift Data Types

Swift Control Flow

Swift Functions

Swift Collections

Swift OOPs

Swift Additional Topics

Swift - If Statement

In Swift, the if statement is used to execute a block of code based on whether a specified condition is true. It's one of the most fundamental control flow constructs in many programming languages.

Syntax:

Here's the basic structure of an if statement:

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

Example:

Let's consider a basic example where we check if a number is positive:

let number = 7

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

// Output: The number is positive.

In this example, since the number 7 is indeed positive, the code inside the if block is executed, and "The number is positive." is printed.

Notes:

  1. Parentheses: In Swift, it's not required to enclose the condition within parentheses (). Both if condition {...} and if (condition) {...} are correct, but the former (without parentheses) is more idiomatic in Swift.

  2. Boolean Condition: The condition inside the if statement should evaluate to a boolean value, i.e., either true or false. If you try to use a non-boolean condition, the Swift compiler will give you an error.

  3. Braces: The curly braces {} are mandatory in Swift, even if there's only one line of code to execute for the condition.

  4. Else and Else If: The if statement can be combined with else and else if to handle multiple conditions or an alternative block of code if the primary condition is false. This allows for more complex decision-making in your code.

Remember, the code inside the if block will only execute if the condition evaluates to true. Otherwise, the program will simply bypass it.

  1. How to use if in Swift programming:

    • Description: The if statement in Swift is a fundamental construct for introducing conditional execution of code.

    • Code:

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

    • Description: if statements in Swift allow you to execute code blocks conditionally based on a Boolean expression.

    • Code:

      let temperature = 25
      
      if temperature > 30 {
          print("It's hot!")
      }
      
  3. Handling boolean conditions in Swift if statements:

    • Description: if statements handle boolean conditions, and the code block is executed when the condition is true.

    • Code:

      let isRaining = true
      
      if isRaining {
          print("Bring an umbrella")
      }
      
  4. Swift if statement with optional binding:

    • Description: Optional binding with if let or guard let ensures safe unwrapping of optionals.

    • Code:

      let optionalValue: Int? = 42
      
      if let unwrappedValue = optionalValue {
          print("Optional has a value: \(unwrappedValue)")
      } else {
          print("Optional is nil")
      }
      
  5. Combining logical operators with if in Swift:

    • Description: Logical operators (&&, ||, !) can be combined to create complex conditions in if statements.

    • Code:

      let isSunny = true
      let isWeekend = false
      
      if isSunny && !isWeekend {
          print("It's a sunny weekday")
      }
      
  6. Using if statements for control flow in Swift:

    • Description: if statements are crucial for controlling the flow of execution in Swift, allowing you to make decisions based on conditions.

    • Code:

      let score = 85
      
      if score >= 90 {
          print("A")
      } else if score >= 80 {
          print("B")
      } else {
          print("C or below")
      }
      
  7. Swift single-line if statement:

    • Description: Single-line if statements can be used when the code block is concise and fits on one line.

    • Code:

      let number = 42
      
      if number % 2 == 0 { print("Even") } else { print("Odd") }