Swift - Using if statement

Introduction

if statements in Swift does not need to wrap the expression you're checking in parentheses:

Demo

if 1+2 == 3 { 
       print("The math checks out") 
}

Result

In Swift, the body of all if statements as well as all loops must be put between two braces { and }.

In C, C++, Java, and Objective-C, you can omit these braces if you just want to have a single statement in your loop or if statement.

In Swift they are mandatory.

Swift else if and else branches as part of your if statements:

Demo

let ifVariable = 5 

if ifVariable == 1 { 
       print("it is one") 
} 
else if ifVariable <= 3 { 
       print("it is less than or equal to three") 
} 
else if ifVariable == 4 { 
       print("it is four") 
} 
else { //  w w  w  .  j av  a  2s .  com
       print("it is something else") 
}

Result

Related Topics

Exercise