if conditional statements are used to execute code block based on conditional expression. Swift provides following conditional statements

It provides the following features

  • simple if statements
  • if else statements
  • if else if else
  • nested if else

Swift if conditional statement

Swift if conditional statement is used to execute code block based on conditional expression statements.

Conditional expression contains either single or multiple conditions.

if conditional expression always evaluated to true or false. if it is true, It executes code block.

Syntax

if condition
    //code block

Here is an example

if condition {
    //code block
    }

condition is an Boolean expression that returns true of false

  • if condition is true, code block is executed.
  • if condition is false, code block not executed. Here is an example for swift if conditional true example
var number=20;
if number%2==0 {
   print("Even Number")
} 

Output:

Even Number

Here is an simple if conditional statement false example

var number=21;
if number%2!=0 {
   print("Odd Number")
} 

Output:

Odd Number

Swift if else conditional statements

if else in swift is used to execute code blocks based on true and false of an conditional expressions.

Syntax:

if condition{
    //code block based on true conditional value
    }
else{
    // code block based on false conditional value
    }

condition is an Boolean expression that returns true of false

  • if condition is true, code block inside if block is executed.
  • if condition is false, code block inside else block is executed. Here is an example for swift if conditional true example

Here is an swift if else conditional expression example

var number=21;
if number%2 == 0 {
   print("Even Number")
} else {
   print("Odd Number")
}

Output:

Odd Number

Swift if else if statement example

This is combination of if else and if statements.

This is used to execute code blocks based on multiple conditions.

Syntax:

if condition1{
    code block executes based on condition1 is true
    }
else if condition2 {
        code block executes based on condition2 is true
        }
else{
    code block executes based on condition1 is false
}

Here is an example

var number=8181;
if number < 9 {  
    print("Single digit number")  
}  
else if (number > 9) && (number<99) {  
    print("Two digit number")  
}  
else if (number > 99) && (number<999) {  
    print("Three digit number")  
}  
else {  
    print("Four digit number")  
}  

Output:

Four digit number