6. Swift: Conditions and Operators

Conditions are very important in all programming languages including Swift. Condition operators compare values and help programmer in taking decisions.

For examples, if a student got 90% marks in exams, he should get ‘A’ grade. If amount in bank account is less than 9000 but greater than 8000 then member is Gold member and so on.

Swift provides following operators which are used with if statment.

1.  AND  operator which is represented by “&&”
2.  OR operator which is represented by “||”
3.  Equality operator “==”
4.  Greater than operator “>”
5.  Less than operator “<”
6.  Greater than equal “>=”
7.  Less than equal “<=”


if and else-if statements

To check the conditions in Swift, you can use “if” statement with curly brackets { }. All lines of code come within these brackets  are called code block. Here is an example:

var studentMarks = 87
var grade = ""

if studentMarks >= 90 {
    grade = "A";
} else if studentMarks >= 80 {
    grade = "B";
} else if studentMarks >= 70 {
    grade = "C";
} else if studentMarks >= 60 {
    grade = "D";
} else {
    grade = "F";
}

As you have noticed that Swift does not use small brackets ( ) with if statement but if you want to add these small brackets, Swift has no objection.

var studentMarks = 89
// marks are greater than equal to 80
if (studentMarks >= 80) {
    println("A")
}

 

AND operator &&

Use ‘and’ operator if you want to validate two conditions. If first and the second both conditions are true then code block will be executed. If one condition is false, the code block will be skipped. Experiment with following code by changing amount values.

var amount = 8000

if amount >= 15000  {
    println("Diamond Member")
} else if amount < 15000 && amount >= 10000 {
    println("Gold Member")
} else if amount < 10000 && amount >= 8000 {
    println("Silver Member")
} else {
    println("Not a member")
}


OR operator ||

If you are using OR (||) operator then you want to validate at least one condition. If only one condition will be true, the code block will be executed.  Experiment with following code by changing value of variables “amount” and “savings”. You can also add more if statement with OR operator

amount = 11000
var savings = 8000

if amount >= 12000 || savings >= 10000{
    println("Gold Member")
} else if amount > 10000 || savings > 9000 {
    println("Silver Member")
} else {
    println("Not a member")
}


Equality operator ==

For equality checking Swift provides “==” 

var x = 5;

if x == 5 {
    println ("Values are equal")
} else {
    println("values are not equal")
}

 

Not Equal Operator !=

Not equal operator is simply opposite of equal operator. If you want to see if your value is not equal to other, use != operator.

var x = 6

if x != 5 {
    println ("Values are not equal")
} else {
    println("values are equal")
}

 

 

Download file from GitHub