Conditionals In Swift With If, Else If, Else

Written by Reinder de Vries on June 10 2018 in App Development

Conditionals In Swift With If, Else If, Else

In Swift you use conditionals to make decisions in your code, with if, else if and else. If this happens, then do that. This is called control flow, because you use it to control the way your code flows.

In this article you’ll learn how to use the if-statement in your Swift code. We’ll get into boolean logic, expressions, operators, and the syntax of if, else if and else blocks.

In practical iOS development you use conditionals all the time. Logic expressions can be especially hard to grasp, but after reading this article you’ll be well equipped to deal with even the most challenging conditionals.

Ready? Let’s go.

  1. Conditional Branching With The If Statement
  2. Expressions And Boolean Logic
  3. Comparison Operators In Swift
  4. Logical Operators: AND, OR, NOT
  5. How To Use If, Else If, Else
  6. Further Reading

Conditional Branching With The If Statement

Conditionals, branching, if-statements – they all mean the same thing: taking decisions in your code. Like this:

if this happens, then do that

A few examples:

  • If the user is logged in, then load her tweets
  • If the tweet includes a photo, then use the MediaTweet UI
  • If the tweet text is not empty, then process the tweet’s hashtags

Making decisions like these is called control flow, or branching, because you split the flow of your code in separate branches.

Conditional Branching Flow Chart

Imagine you create many of these decisions like the one above, and you see that the flow of your code quickly branches out in many directions. Kinda like a tree!

Let’s take a look at the Swift syntax for conditionals. Here’s an example:

if password == "Open sesame!" {
    cave.open()
    treasure.steal()
}

A few things are happening here:

  • The expression password == "Open sesame!" uses boolean logic to determine whether password is equal to the string Open sesame!
  • When this expression evaluates to true, the code between the squiggly brackets { and } is executed. This is the conditional body.

In other words: if the password is “Open sesame!” then open the cave and steal the treasure!

You’ve seen those squiggly brackets { and } before, in functions and in classes. They’re used throughout programming to structure blocks of code. Whenever a function is called, or a conditional is true, the block of code between { and } is executed.

Expressions, like password == "Open sesame!", are more complicated. Let’s figure out how that works, in the next chapter.

Learn how to build iOS apps

Get started with iOS 12 and Swift 4

Sign up for our iOS development course Zero to App Store and learn how to build professional iOS 12 apps with Swift 4 and Xcode 10.

Expressions And Boolean Logic

If you’re familiar with math, you know that the expression 3 + 4 + 5 produces the result 12. In programming, you can create expressions too:

let circumference = 2 * .pi * radius

The expression 2 * .pi * radius produces the circumference of a circle, based on its radius. The result of the expression is 94.24 in the following example:

let radius = 15.0
let circumference = 2 * .pi * radius

print(circumference)

An expression is a combination of one or more values, constants, variables, operators, and functions that Swift interprets and computes to produce a return value. This process is called evaluation.

Said differently: you can combine numbers, variables and functions to create an expression of a particular value. This value can then be assigned to a variable, like circumference and radius in the example above.

One kind of expression is exceptionally powerful: the boolean expression. This expression uses boolean logic to return either true or false. Its type in Swift is Bool.

Let’s look at an example:

let isLoggedIn:Bool = false

if isLoggedIn {
print("*** SECRET MESSAGE ***")
}

Use the Swift Sandbox above to do this:

  1. First, run the Sandbox by clicking Run
  2. Then, change the value of isLoggedIn to true
  3. Finally, run the Sandbox again

Did you see what happened?

  • If isLoggedIn is false, the conditional is not executed, and the secret message is not shown
  • If isLoggedIn is true, the conditional is executed, and the secret message is shown

That’s boolean logic right there! The if-statement evaluates the value of isLoggedIn and acts accordingly. When the value is true, the conditional body is executed. When the value is false, the conditional body is not executed.

You don’t always use conditionals to check for functional logic in your code, such as “is the user logged in” or “is the password correct”. You also use conditionals to check the state of your code, and to validate data that’s passed around.

Imagine the following scenario:

  • Your UI has two buttons: loginButton and signupButton
  • You use one function to respond to taps on both buttons, called onButtonTapped(button:)
  • Inside the function you compare the button parameter against the loginButton and the signupButton with:
    if button == loginButton {
        // Do stuff...
    } else if button == signupButton {
        // Do something else ...
    }
    
  • Now you know which button was tapped, and you can act accordingly

This conditional has nothing to do with interactions in your app. It acts upon the data within your code. Let’s look at some more advanced examples of conditionals, in the next chapters.

Why is it called boolean logic? It’s named after mathematician George Boole (1815-1864), who laid the groundwork for Boolean algebra. Boolean expressions produce either true or false, called truth values, often denoted as 1 or 0 respectively. These two values lie at the basis of digital systems, like computers and apps.

Comparison Operators In Swift

The expression in if isLoggedIn { ... is checking if the value of isLoggedIn is equal to true. So it’s exactly the same as this:

if isLoggedIn == true {
    // Do stuff...
}

Do you see that ==? It’s a comparison operator, and you use it to check if two values are equal.

Swift has the following comparison operators:

  • Equal to: a == b
  • Not equal to: a != b
  • Greater than: a > b
  • Less than: a < b
  • Greater than or equal to: a >= b
  • Less than or equal to: a <= b

You use comparison operators to compare values with each other. You typically use >, <, >= and <= with numerical values, whereas == and != are typically used to find out if any two values are the same or not.

Swift also has two identity operators, === and !==, that test if two references both refer to the exact same object.

Let’s look at an example:

let room = 101

if room >= 100 {
print("This room is on the first floor...")
}

The expression room >= 100 tests if the constant room is greater than or equal to 100. Because room is 101, the expression returns true and the conditional body is executed. Can you change the code to something else, to see how it works?

When you compare two values, they both need to have the same type. It does not make sense to test if a string is equal to an integer. They’ll never be equal, because they both have different types.

The code below results in a compiler error, because room and input have different types.

let room:Int = 123
let input:String = "123"

if room == input {
print("This room is available!")
}

What if you need to compare a string value with an integer value? You’ll need to parse the string and convert it to an integer, or convert the integer to a string. When both types are related, you can also use type casting.

You already know about optionals in Swift, right? You can use the equality operators == and != to compare an optional with a non-optional value, but you can’t use >, <, >= and <= to compare optionals without unwrapping them.

Interestingly, you can compare strings with each other, using all of the ==, != and even >, <, >=, <= operators! So we can test whether “abcd” is less than “efgh”. Like this:

"abcd" < "efgh"
// Result: true

This is exceptionally useful for sorting string values, for instance to order names alphabetically:

var names = ["Dolores", "Bernard", "Arnold"]
names.sort(by: <)
print(names)

Alright, let’s move on to the next set of operators!

Logical Operators: AND, OR, NOT

A boolean expression with just one condition is a bit boring, so let’s spice it up with the logical operators AND, OR and NOT.

Check this out:

var isPresident = true
var threatLevel = 7
var officerRank = 3

if (threatLevel > 5 && officerRank >= 3) || isPresident
{
print("FIRE ROCKETS!!!")
}

In the above example, you can fire rockets if

  • isPresident is true OR
  • threatLevel is greater than 5 AND officerRank is greater than or equal to 3

See how you’re using logical operators to create a combination of boolean expressions? You’re also using comparison operators to assess the value of threatLevel and officerRank.

There are 3 different logical operators:

  • AND, denoted by &&
  • OR, denoted by ||
  • NOT, denoted by !

Both AND and OR are infix operators, so you put them between two values, like a && b and a || b. The NOT operator is a prefix, so you put it before one value, like !a.

  • An expression with the AND operator returns true when both of its operands are true. When either operand is false, it returns false.
  • An expression with the OR operator returns true when either of its operands are true. When both are false, the OR operator returns false.
  • An expression with the NOT operator returns the opposite of its value, so true when false, and false when true.

What are operands? In an expression a + b, the + is the operator, and a and b are operands. The operator affects the operands.

That’s complicated stuff, right? Let’s put those expressions in a Truth Table, like this:

a b AND OR
true true true true
true false false true
false true false true
false false false false

You can read the Truth Table like this:

  • Row 1: When both a and b are true, both AND and OR return true
  • Row 2-3: When a is true and b is false, or vice versa, AND returns false and OR returns true
  • Row 4: When both a and b are false, both AND and OR return false

And a Truth Table for the NOT operator is simple, like this:

a NOT
true false
false true

The NOT operator inverts true and false. So when a = false, the expression !a returns true. This is exactly the same as a == false, which also returns true.

Can you ascertain the result of the expression !(!false)? It’s not not false, which is not true, which is false. Mind-boggling!

That’s quite theoretical, so let’s put it into practice. We’re going to play around with the previous example, this one:

var isPresident = true
var threatLevel = 7
var officerRank = 3

if (threatLevel > 5 && officerRank >= 3) || isPresident
{
print("FIRE ROCKETS!!!")
}

You can break that expression down in two parts. We’ll start at the deepest level, inside the parentheses:

threatLevel > 5 && officerRank >= 3

This expression combines two expressions, namely threatLevel > 5 and officerRank >= 3. They’re connected with the AND logical operator. So, the entire expression will only result in true when both the threatLevel is greater than 5 and the officerRank is greater than or equal to 3.

The second part of the expression is this:

(X) || isPresident

In the above code (X) is the result of the previous expression threatLevel > 5 && officerRank >= 3. We’re combining the result of that expression with isPresident and the OR operator ||.

When either of the expressions threatLevel > 5 && officerRank >= 3 or isPresident is true, the entire expression returns true.

Consider that treatLevel = 7, officerRank = 3 and isPresident = true. We can then resolve every expression step by step, like this:

(threatLevel > 5 && officerRank >= 3) || isPresident
(true && officerRank >= 3) || isPresident
(true && true) || isPresident
true || isPresident
true || true
true

What if threatLevel = 4, officerRank = 5 and isPresident = false? Then you can evaluate the expressions like this:

(threatLevel > 5 && officerRank >= 3) || isPresident
(false && officerRank >= 3) || isPresident
(false && true) || isPresident
false || isPresident
false || false
false

See how that works? Awesome!

Important question: If isPresident is true, does it matter what the threatLevel and the officerRank is? (Answer for yourself! Correct answer at end of article.)

How To Use If, Else If, Else

Alright, last but not least: the syntax for if, else if and else. You can combine multiple conditionals into one chain. Like this:

let color = "purple"

if color == "green"
{
print("I love the color \(color)!")
}
else if color == "blue" || color == "purple"
{
print("I kinda like the color \(color)...")
}
else
{
print("I absolutely HATE the color \(color)!!!")
}

In the above example you’ve combined several if-statements into one conditional, using if, else if and else. Here’s how it works:

  • First, you declare a constant color of type String, and assign the string "purple" to it.
  • Then, the expression color == "green" is evaluated. When that expression results in true, the first { } block is executed, and every other expression after that is skipped. When the expression results in false, the first { } block is not executed, and the code continues to evaluate the next expression.
  • Assuming that the previous expression returned false, the expression color == "blue" || color == "purple" is evaluated. When it returns true, the code block is executed, and when it is false, the code continues to evaluate the next expression.
  • Assuming that none of the previous expressions returned true, the else block is invoked. This is a “catch all” when all the other conditional expressions failed, and returned false.

You can deduce a few rules about if, else if and else from the above examples.

  • Execution of the conditional starts at the top, and continues to the bottom
  • When an expression returns true, that conditional body is executed, and the others are skipped over
  • When an expression returns false, the conditional body is skipped over, and the next expression is evaluated
  • When none of the expressions have returned true, the else block is executed

Conditionals like the one above are not evaluated “as a whole”. Instead, their expressions are evaluated one by one.

A conditional needs to include at least one if statement. It can optionally include one else statement, and it can optionally include one or more else if statements.

Let’s look at another example:

let isLoggedIn = false

if isLoggedIn {
print("*** SECRET MESSAGE ***")
} else {
print("ACCESS DENIED!")
}

In the above example, the else block is executed, because isLoggedIn is false. Said differently: isLoggedIn is not true, so the first block is not executed, and consequently the else block is executed.

A common misconception is that an else block is executed when the expression in the first block is false. This is correct in the above example. But what about the following code…

if name == "Bob" {
    print("Only Bob is allowed to pass.")
} else {
    print("YOU SHALL NOT PASS!")
}

In this example, the else block is executed for any value of name that is not "Bob". The else block is really a “catch all” when all of the earlier expressions failed.

OK, let’s look at one last example:

var isPresident = true
var threatLevel = 7
var officerRank = 3

if threatLevel > 5 && officerRank >= 3 {
print("FIRE ROCKETS!!! (as officer)")
} else if isPresident {
print("FIRE ROCKETS!!! (as president)")
} else {
print("CANNOT FIRE ROCKETS...")
}

The above example has the exact same effect as the previous examples, except that its implementation is now different. Do you see the difference?

Instead of firing rockets when the threatLevel, officerRank and isPresident variables have the correct values, you now respond to individual cases. As a result, only one of these conditionals is executed.

Here’s a few things you can try:

  • Can you switch the threatLevel ... and isPresident expressions? How does that affect execution?
  • Imagine that both a president and a high-ranking officer have their hand on the rocket launch button. Who presses it first?
  • Can you break up the threatLevel > 5 && officerRank >= 3 in two else if expressions? Does this affect the conditions under which a rocket launch is allowed?
  • Do you know when the else clause will be executed, based on the state of the 3 variables?

Happy coding!

Learn how to build iOS apps

Get started with iOS 12 and Swift 4

Sign up for our iOS development course Zero to App Store and learn how to build professional iOS 12 apps with Swift 4 and Xcode 10.

Further Reading

Conditionals are awesome, right? If this happens, then do that. You use that to take decisions in your code, and to “branch out” into different states and scenarios.

This is what you’ve learned:

  • How to use conditionals with if to take decisions in your code
  • How boolean expressions affect the execution of conditionals
  • How to use logical operators and comparison operators
  • How the syntax of if, else if and else works

Want to learn more? Check out these resources:

When isPresident is true, it does not matter what threatLevel and officerRank are. The expression a || b returns true if a or b is true, and it doesn’t matter which one. However, in the else if example, when the threatLevel and officerRank are high enough, the officer will launch the rockets before the president, even when isPresident is true.

Reinder de Vries

Reinder de Vries

Reinder de Vries is a professional iOS developer. He teaches app developers how to build their own apps at LearnAppMaking.com. Since 2009 he has developed a few dozen apps for iOS, worked for global brands and lead development at several startups. When he’s not coding, he enjoys strong espresso and traveling.