Swift if...else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax
The syntax for the if...else statement in Swift:
if boolean_expression {
/* Statements to execute if the Boolean expression is true */
} else {
/* Statements to execute if the Boolean expression is false */
}
If the Boolean expression is true, the code inside the if block is executed. If the Boolean expression is false, the code inside the else block is executed.
Flowchart
Example
import Cocoa
var varA:Int = 100;
/* Check the Boolean condition */
if varA < 20 {
/* Execute the following statement if the condition is true */
print("varA is less than 20");
} else {
/* Execute the following statement if the condition is false */
print("varA is greater than 20");
}
print("The value of varA is \(varA)");
When the above code is compiled and executed, it produces the following result:
varA is greater than 20
The value of varA is 100