Swift - If Statement



An if statement consists of a Boolean expression followed by one or more statements.

Syntax

The syntax of an if statement in Swift 4 is as follows −

if boolean_expression {
   /* statement(s) will execute if the boolean expression is true */
}

If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.

Flow Diagram

If Statement

Example

import Cocoa

var varA:Int = 10;

/* Check the boolean condition using if statement */
if varA < 20 {
   /* If condition is true then print the following */
   print("varA is less than 20");
}
print("Value of variable varA is \(varA)");

When we run the above program using playground, we get the following result.

varA is less than 20
Value of variable varA is 10
swift_decision_making.htm
Advertisements