Control Flow

If Statement in Swift

The if else block controls decision making by checking true/false statements resulting in different executions of code, depending on if the result is true and if the result is false.

There are three parts to the if-else block: if, else if, and else.


Syntax
if booleanExpression { 
    //Executes when booleanExpression holds true  
} 
else if booleanExpression2 { 
    //Executes when booleanExpression2 holds true
} 
else { 
    //Executes when neither booleanExpression nor booleanExpression2 are true
}

Notes

In Swift, assignment expressions can be used in an if statement. Often times, the assignment expression is an optional.

booleanExpression(s) are those that result in either a true or false output. They are created using comparing operators (==, ===, >, =, <=, !=).

There can also be multiple Boolean expressions within the parentheses (booleanExpression). The Boolean expressions are connected through logical operators (&&, ||, !).

Else if statements allow for another Boolean expression check within the overall if structure. This is optional.

Else statements result in the execution of code if the if statement (and if applicable, the subsequent else if statement(s)) do not hold true.

Nested if (else) statements are also possible and are the inclusion of another (or multiple) if statements within an if statement block.


Example
int counter = 5

if counter >= 30 { 
    print "Counter is greater than or equal to 30."
} 
else if counter == 20 { 
    print "Counter is at 20." 
    ++counter
} 
else { 
    ++counter
}

< Enumerations   |   Switch Case >

© 2019 SyntaxDB. All Rights Reserved.