If-Else Statement in Swift



In this tutorial, we will learn about if-else statements in Swift. We will cover the basics of conditional execution using if-else statements.


What is an If-Else statement

An if-else statement is a conditional statement that executes one block of code if a specified condition is true, and another block of code if the condition is false.


Syntax

The syntax for the if-else statement in Swift is:

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

The if-else statement evaluates the specified condition. If the condition is true, the code block inside the if statement is executed; otherwise, the code block inside the else statement is executed.

Flowchart of If Else Statement


Example 1: Checking if a Number is Even or Odd

  1. Declare a variable num.
  2. Assign a value to num.
  3. Use an if-else statement to check if num is even or odd.
  4. Print a message indicating whether num is even or odd.

Swift Program

let num = 10
if num % 2 == 0 {
    print("\(num) is even.")
} else {
    print("\(num) is odd.")
}

Output

10 is even.


Example 2: Checking if a String Starts with a Specific Value

  1. Declare a variable str.
  2. Assign a value to str.
  3. Use an if-else statement to check if str starts with a specific value.
  4. Print a message indicating the result of the check.

Swift Program

let str = "Hello, world!"
if str.hasPrefix("Hello") {
    print("String starts with 'Hello'.")
} else {
    print("String does not start with 'Hello'.")
}

Output

String starts with 'Hello'.


Example 3: Checking if a Number is Positive or Negative

  1. Declare a variable num.
  2. Assign a value to num.
  3. Use an if-else statement to check if num is positive or negative.
  4. Print a message indicating whether num is positive or negative.

Swift Program

let num = -5
if num > 0 {
    print("\(num) is positive.")
} else {
    print("\(num) is negative or zero.")
}

Output

-5 is negative or zero.