# Lesson 4 - Conditions (branching) in Swift

Swift Basic constructs Conditions (branching) in Swift

In the previous lesson, More on the Swift type system: Data types, we discussed Swift data types in details. We need to react somehow to different situations if we want to program something. It may be, for example, a value entered by the user, according to which we would like to change the running of the program. We metaphorically say that the program branches, and for branching we use conditions. We will pay attention to those in today's Swift tutorial. We're going to create a program which calculates square roots, and which we're going to use to improve our calculator.

## Conditions

In Swift, conditions are exactly the same as in all C-like languages, either way, I will explain everything for beginners. Advanced programmers will probably be bored for a moment

We write conditions using the `if`

keyword, which is followed by a
logical expression. If the expression is true, the following statement will be
executed. If it's not true, the following statement will be skipped, and the
program will continue with the next statement. Let's try it out:

if 15 > 5 { print("True") } print("The program continues here...")

The output:

True The program continues here...

If the condition is true, the command which writes text to the console will
be executed. In both cases the program continues. In Swift, you can't write
`if`

without braces. Of course, a variable can also be part of the
expression:

print("Enter a number") var a = Int(readLine()!)! if (a > 5) { print("The number you entered is greater than 5!") } print("Thanks for the input!")

Let's look at the relational operators which we can use in expressions:

Meaning | Operator |
---|---|

Equal to | == |

Greater than | > |

Less than | < |

Greater than or equal to | >= |

Less than or equal to | <= |

Not equal | != |

Negation | ! |

We use the `==`

operator for equality to avoid confusing it with a
normal assignment to a variable (the `=`

operator). If we want to
negate an expression, we enclose it in parentheses and write an exclamation mark
before the expression. Of course, we can execute more than one command in the
condition block:

print("Enter a number and I'll get its square root:") let a = Int(readLine()!)! if a > 0 { print("The number you entered is greater than 0, so I can calculate it!") let root = sqrt(Double(a)) print("The square root of \(a) is \(root)") } print("Thanks for the input")

The output:

Enter a number and I'll get its square root: 144 The number you entered is greater than 0, so I can calculate it! The square root of 144 is 12.0 Thanks for the input!

The program retrieves a number from the user, and if it's greater than
`0`

, it calculates the square root. The `sqrt()`

function
returns the square root as `Double`

but we have to convert our input
to `Double`

first. It'd be nice if our program warned us if we
entered a negative number. With what we know up until now, we could write
something like this:

print("Enter a number and I'll get its square root:") let a = Int(readLine()!)! if a > 0 { print("The number you entered is greater than 0, so I can calculate it!") let root = sqrt(Double(a)) print("The square root of \(a) is \(root)") } if a <= 0 { print("I can't calculate the square root of a negative number!") print("Thanks for the input")

We must keep in mind the case where `a == 0`

, but also when it's
less than 0. The code can be greatly simplified by using the
** else** keyword which executes the following
statement or block of statements

**if the condition was not true**:

print("Enter a number and I'll get its square root:") let a = Int(readLine()!)! if (a > 0) { print("The number you entered is greater than 0, so I can calculate it!") let root = sqrt(Double(a)) print("The square root of \(a) is \(root)") } else { print("I can't calculate the square root of a negative number!") } print("Thanks for the input")

The code is much clearer, and we don't have to make up the negate condition which could be very difficult with complex conditions sometimes.

We also use the `else`

keyword when we need to modify the variable
used in a condition so we can't evaluate it later again. The program remembers
that the condition didn't apply and it'll move to the `else`

branch.
Let's look at an example: Consider a number which value will be either
`0`

or `1`

and we'll be asked to swap those values (if
there is `0`

, we'll put a `1`

there, and the other way
around). Naively, we could write a code like this:

int a = 0 // the variable is initialized with a value of 0 if a == 0 { // if the value is 0, we change its value to 1 a = 1 } if a == 1 { // if the value is 1, we change its value to 0 a = 0 } print(a)

It doesn't work, does it? Let's take a closer look at the program. At the
very beginning, `a`

contains the value `0`

, the first
condition is undoubtedly fulfilled and it assigns `1`

into
`a`

. Well, suddenly, the second condition becomes true as well. What
should we do? When we swap the conditions, we'll have the same problem with
`1`

. Now, how do we solve this? You guessed it, using
`else`

!

int a = 0 // the variable is initialized with a value of 0 if a == 0 { // if the value is 0, we change its value to 1 a = 1 } else { // if the value is 1, we change its value to 0 a = 0 } print(a)

Conditions can be composed by using two basic logical operators:

Operator | C-like syntax |
---|---|

Logical AND | && |

Logical OR | || |

Let's take a look at the example:

print("Enter a number between 10-20:") let a = Int(readLine()!)! if a >= 10 && a <= 20 { print("The condition has been met.") } else { print("You did it wrong.") }

Of course operators can be combined with parentheses:

print("Enter a number between 10-20 or 30-40:") let a = Int(readLine()!)! if (((a >= 10) && (a <= 20)) || ((a >=30) && (a <= 40))) { print("The condition has been met.") } else { print("You did it wrong.") }

## Switch

`switch`

is a construct taken from the C language, like most of Swift's syntax. It
allows us to relatively simplify the usage of `if`

-`else`

command sequences. Let's remember our calculator from the first lesson, which
had read two numbers and calculated all 4 operations. Now, we want to choose the
operation. Without the `switch`

, we'd write the code like this:

print("Welcome to our calculator") print("Enter the first number:") let a = Double(readLine()!)! print("Enter the second number:"); let b = Double(readLine()!)! print("Choose one of the following operations:") print("1 - addition") print("2 - subtraction") print("3 - multiplication") print("4 - division") let choice = Int(readLine()!)! var result : Double = 0 if choice == 1 { result = a + b } else if choice == 2 { result = a - b } else if choice == 3 { result = a * b } else if choice == 4 { result = a / b } if (choice > 0) && (choice < 5) { print("Result: \(vysledek)") } else { print("Invalid choice") } print("Thank you for using our calculator.")

The output:

Welcome to our calculator Enter the first number: 3.14 Enter the second number: 2.72 Choose one of the following operations: 1 - addition 2 - subtraction 3 - multiplication 4 - division 2 Result: 0.42 Thank you for using our calculator

Notice that we've declared the variable `result`

at the beginning,
so we could later assign something to it. If we declared it at every assignment,
Swift would not compile the code and report an error since the variable would be
already declared. A variable can be declared (initialized in memory) only once.
Unfortunately, Swift is not able to tell whether a value has been already
assigned to the `result`

variable. It would report an error on the
line where we're printing to the console because it doesn't like the fact that
the variable being printed is not guaranteed to contain a value. For this
reason, we have to assign *zero* to the `result`

variable at
the beginning. Another trick is validating the user's choice. The program should
still work the same even without all the `else`

s (but why keep on
asking if we already have a result).

Now here's the same program using `switch`

:

print("Welcome to our calculator") print("Enter the first number:"); let a = Double(readLine()!)! print("Enter the second number:") let b = Double(readLine()!)! print("Choose one of the following operations:") print("1 - addition") print("2 - subtraction") print("3 - multiplication") print("4 - division") let choice = Int(readLine()!)! var result : Double = 0 switch (choice) { case 1: result = a + b case 2: result = a - b case 3: result = a * b case 4: result = a / b default: break } if (choice > 0) && (choice < 5) { print("Result: \(result)") } else { print("Invalid choice") } print("Thank you for using our calculator.")

As you can see, the code is a bit clearer now. If we needed to execute
multiple commands in any branch of the `switch`

, we wouldn't
surprisingly write them inside a `{}`

block, but just under the first
command. For those who have used other programming languages before: you don't
have to terminate every case with `break`

to make sure the cases
below won't execute. Swift, in case of `switch`

, executes only one
`case`

. The `switch`

construct can also contain
`default:`

which will be executed if neither of the cases applied.
You should have the default block in your switches, unless you have already
covered all the possibilities in the case blocks. It's up to you whether you use
`switch`

or not. Generally, it's useful only for a larger amount of
branches and you can always replace it with an `if`

-`else`

sequence. Of course, `switch`

can be used for `String`

variables as well.

That is all for today. In the next lesson, Loops in Swift, we'll take a look at arrays and loops, i.e. finish up with the absolute basics of the Swift language. Look forward to it

### Download

Downloaded 2x (67.77 kB)

**Comments**

No one has commented yet - be the first!