if conditional statements are used to execute code blocks based on a conditional expression. Swift provides the 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 the conditional statement is used to execute code block based on conditional expression statements.
The conditional expression contains either single or multiple conditions.
if the conditional expression is always evaluated as true or false. if it is true, It executes a code block.
Syntax
if condition
//code block
Here is an example
if condition {
//code block
}
condition is a Boolean expression that returns true or false
- if the condition is true, the code block is executed.
- if the condition is false, the code block is not executed. Here is an example of a swift if conditional true example
var number=20;
if number%2==0 {
print("Even Number")
}
Output:
Even Number
Here is a 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 conditional expressions.
Syntax:
if condition{
//code block based on true conditional value
}
else{
// code block based on false conditional value
}
condition is a Boolean expression that returns true or false
- if the condition is true, code block inside if block is executed.
- if the condition is false, the code block inside the else block is executed. Here is an example of a swift if conditional true example
Here is a 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 a 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 the condition1 is true
}
else if condition2 {
code block executes based on the condition2 is true
}
else{
code block executes based on the 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