Here we will learn if else condition or statement in swift with examples and how to use swift if else statement to execute set of statements if defined condition is TRUE otherwise execute else condition statements with examples.
In swift, if else statement is used to add alternative set of else statements for if condition. In case if condition fails (FALSE) then alternatively it will execute else statements.
Whenever we have specific requirement like execute set of block statements if given condition is TRUE else execute other statements in that situation we can use swift if else statement.
Now we will see the functionality of if else statement in swift programming language using algorithm diagram.
Following is the swift if else statement flow diagram to represent how the functionality of if else statement will work in swift programming language.
If you observe above swift if else statement flow diagram first it will evaluates the given condition is TRUE or FALSE. If given condition is TRUE then it will execute the code block within if statement. In case the given condition is FLASE then it will execute else condition code block and reach the end of statement.
Following is the syntax of if else statement in swift programming language.
If condition
{
//Expressions will execute when condition TRUE
}
else
{
//Expressions will execute when if condition fails
}
If you observe above swift if else statement syntax first it will evaluates if condition if it TRUE then it will execute if condition expression otherwise it will execute else condition expressions.
Now we will see how to use if else statement in swift programming language with examples.
Following is the simple example using if else statement in swift to check the condition before execute the expressions within the condition.
var num1: Int = 10
if num1 > 20 {
print("Number Greater than 20")
}
else {
print("Number Less than 20 ")
}
If you observe above example we are checking the condition whether the value of “num1” greater 20 or not.
When we execute above code in swift playground we will get result like as shown below.
This is how we can use swift if else statement to execute expressions based on our defined conditions.