Home > Articles > Programming > General Programming/Other Languages

Conditionals in Swift

  • Print
  • + Share This
This chapter from Swift Programming: The Big Nerd Ranch Guide introduces conditionals in Swift, including if/else, ternary operator, nested ifs, and else if.
This chapter is from the book

In previous chapters your code led a relatively simple life: you declared some simple constants and variables and then assigned them values. But of course, an application really comes to life – and programming becomes a bit more challenging – when the application makes decisions based on the contents of its variables. For example, a game may let players leap a tall building if they have eaten a power-up. You use conditional statements to help applications make these kind of decisions.

if/else

if/else statements execute code based on a specific logical condition. You have a relatively simple either/or situation and depending on the result one branch of code or another (but not both) runs. Consider Knowhere, your small town from the previous chapter, and imagine that you need to buy stamps. Either Knowhere has a post office or it does not. If it has a post office, you will buy stamps there. If it does not have a post office, you will need to drive to the next town to buy stamps. Whether there is a post office is your logical condition. The different behaviors are “get stamps in town” and “get stamps out of town.”

Some situations are more complex than a binary yes/no. You will see a more flexible mechanism called switch in Chapter 5. But for now, let’s keep it simple.

Create a new OS X playground and name it Conditionals. Enter the code below, which shows the basic syntax for an if/else statement:

Listing 3.1 Big or small?

import Cocoa

var population: Int = 5422
var message: String

if population < 10000 {
    message = "\(population) is a small town!"
} else {
    message = "\(population) is pretty big!"
}

print(message)

You first declare population as an instance of the Int type and then assign it a value of 5422. Next, you declare a variable called message that is of the String type. You leave this variable uninitialized at first, meaning that you do not assign it a value.

Next comes the conditional if/else statement. This is where message is assigned a value based on whether the “if” statement evaluates to true. (Notice that you use string interpolation to put the population into the message string.)

Figure 3.1 shows what your playground should look like. The console and the results sidebar show that message has been set to be equal to the string literal assigned when the conditional evaluates to true. How did this happen?

Figure 3.1

Figure 3.1 Conditionally describing a town’s population

The condition in the if/else statement tests whether your town’s population is less than 10,000 via the < comparison operator. If the condition evaluates to true, then message is set to be equal to the first string literal (“X is a small town!”). If the condition evaluates to false – if the population is 10,000 or greater – the message is set to be equal to the second string literal (“X is pretty big!”). In this case, the town’s population is less than 10,000, so message is set to “5422 is a small town!”

Table 3.1 lists Swift’s comparison operators.

Table 3.1 Comparison operators

Operator

Description

<

Evaluates whether the number on the left is smaller than the number on the right.

<=

Evaluates whether the number on the left is smaller than or equal to the number on the right.

>

Evaluates whether the number on the left is greater than the number on the right.

>=

Evaluates whether the number on the left is greater than or equal to the number on the right.

==

Evaluates whether the number on the left is equal to the number on the right.

!=

Evaluates whether the number on the left is not equal to the number on the right.

===

Evaluates whether the two instances point to the same reference.

!==

Evaluates whether the two instances do not point to the same reference.

You do not need to understand all of the operators’ descriptions right now. You will see many of them in action as you move through the book, and they will become clearer as you use them. Refer back to this table as a reference if you have questions.

Sometimes you only care about one aspect of the condition that is under evaluation. That is, you want to execute code if a certain condition is met and do nothing if it is not. Enter the code below. (Notice that new code, shown in bold, appears in two places.)

Listing 3.2 Is there a post office?

import Cocoa

var population: Int = 5422
var message: String
var hasPostOffice: Bool = true

if population < 10000 {
    message = "\(population) is a small town!"
} else {
    message = "\(population) is pretty big!"
}

print(message)

if !hasPostOffice {
    print("Where do we buy stamps?")
}

Here, you add a new variable called hasPostOffice. This variable has the type Bool, short for “Boolean.” Boolean types can take one of two values: true or false. In this case, the Boolean hasPostOffice variable keeps track of whether the town has a post office. You set it to true, meaning that it does.

The ! is called a logical operator. This operator is known as “logical not.” It tests whether hasPostOffice is false. You can think of ! as inverting a Boolean value: true becomes false, and false becomes true.

The code above first sets hasPostOffice to true, then asks whether it is false. If hasPostOffice is false, you do not know where to buy stamps, so you ask. If hasPostOffice is true, you know where to buy stamps and do not have to ask, so nothing happens.

Because the town does have a post office (because hasPostOffice was initialized to true), the condition !hasPostOffice is false. That is, it is not the case that hasPostOffice is false. Therefore, the print() function never gets called.

Table 3.2 lists Swift’s logical operators.

Table 3.2 Logical operators

Operator

Description

&&

Logical AND: true if and only if both are true (false otherwise)

||

Logical OR: true if either is true (false only if both are false)

!

Logical NOT: true becomes false, false becomes true

  • + Share This
  • 🔖 Save To Your Account