Conditionals In Swift With If, Else If, Else

In Swift you use conditionals to make decisions in your code, with if, elseif 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, elseif 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.

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 13 and Swift 5

Sign up for my iOS development course, and learn how to build great iOS 13 apps with Swift 5 and Xcode 11.

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)

Hide warnings

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 ***")
}

Hide warnings

Use the Swift Sandbox above to do this:

First, run the Sandbox by clicking Run

Then, change the value of isLoggedIn to true

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:

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...")
}

Hide warnings

The expression room >= 100 tests if the constant room is greater than or equal to100. 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!")
}

Hide warnings

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:

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 5and 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 >= 3orisPresident 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:

In the above example you’ve combined several if-statements into one conditional, using if, elseif 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, elseif 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 elseif statements.

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…

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 twoelseif 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 13 and Swift 5

Sign up for my iOS development course, and learn how to build great iOS 13 apps with Swift 5 and Xcode 11.

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 elseif example, when the threatLevel and officerRank are high enough, the officer will launch the rockets before the president, even when isPresident is true.

Browse Topics

Swift Sandbox

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.