Chapter 8: Boolean Logic & Conditional Statements

In this chapter, we will discuss Booleans, Conditionals, and Comparison Operators. Booleans are a foundational piece of programming that you will use throughout your code. They are used to compare things or perform an action based on a condition.


What you will learn

  • Creating your first Boolean
  • Type Inference
  • Conditional Statement Basics
  • Comparison Operators

Key Terms

  • Boolean: a binary variable, having two values – “true” and “false.”
  • Conditional Statement: a block of code with one or two conditions that only runs when certain requirements are met.
  • Comparison Operator: a function used to determine equality, inequality, or difference between two.

When you were a kid, there may have been a time where your parents said, "if you clean your room", then ___ would be the reward. You can fill in the blank. A trip to Disneyland ✈️? A Japanese-imported Robby the Robot toy 🤖? Perhaps a near-mint copy of Action Comics No.1 "Superman" 📚?

But if you failed to clean your room, then the consequence would be not getting that reward.

If x is true, then y happens. Otherwise, z happens. This "cause and effect" relationship is the foundation that Booleans rest on.

Simply put, a Boolean is true or false.

Creating your first Boolean

First, open Xcode if you haven't already and click Create New Playground. Give it a name like BooleansConditionalsComparisonOperators and click Next. Choose somewhere to save this .playground file and click Create to save it. You should see a screen like the one in Figure 3.1.

Figure 1.8.1 Screen Shot 2016-10-10 at 5.01.11 AM.png

Delete all the boilerplate code on the left side but leave import UIKit as that is necessary.

Type the following code:

var isThisTheBestBookEver = true

You should see on the right-hand side, that the variable is equal to true.

Since we have declared our variable isThisTheBestBookEver as true, we have actually used one of Swift's most helpful features – Type Inference!

Swift Magic: Type Inference

Remember back to Chapter 3 where we learned that variables can be of many types: Characters or words (String), numbers (Int, Float, Double), or even of type Bool (short for Boolean).

Thanks to Swift, we don't need to tell Xcode that we are declaring a Boolean when we type true or false because those are the only two values that a Boolean can be. In Chapter 3, when we wrote the following code, we used Type Inference as well:

var message = "Insert String information here..."

We used quotation marks (") to help Swift infer that the variable we wrote was of type String.

To explicitly declare a variable you can use the following syntax:

var message: String = "Insert String Information here..."

//or

var isThisTheBestBookEver: Bool = true

Thanks to Swift, we don't need to explicitly declare these types, although at times it is necessary which I will explain later on.

Back To Bools

Alright, now that we understand Type Inference, let's journey back over to our Swift Playground in Xcode.

We left the following code in our Playground:

var isThisTheBestBookEver = true

Beneath that code, we're going to change the value of our variable to now be false.

var isThisTheBestBookEver = true
isThisTheBestBookEver = false

By writing the name of our variable and setting it to be equal to false it is now false!


Helpful Hint: Only return a Boolean value for the sake of making a decision. It returns a true or false value, so it is perfect for making these kinds of decisions.


Conditional Statement Basics

Conditional statements help our code make decisions and run code depending on certain conditions. We can use conditionals to check against all kinds of values and conditions.

Write the following if statement and if/else statement at the bottom of your Playground:

var numberOfMinutes = 525600
var hasMedals = true

if numberOfMinutes == 525600 {
    print("Time to pay the rent.")
}

if hasMedals == true {
    print("You're amazing, Felix! Let's have a party!")
} else {
    print("Go away, Ralph!")
}

As you can see in the console, the first if statement prints out "Time to pay the rent." And the second if/else statement prints out "You're amazing, Felix! Let's have a party!".

If you want to add a third condition, you can also use else if like so:

let num = 9

if num < 0 {
    print("Number is negative.")
} else if num < 10 {
    print("Number is single-digit.")
} else {
    print("Number is multi-digit")
}

The above code will print "Number is single-digit." because num is less than 10.

In the rest of this chapter, we will use conditionals and comparison operators together in new and exciting ways. 🤘

Comparison Operators

Declaring something as true or false is great and all, but what can we actually do with it? We can use Comparison Operators to make our code compare things!

To begin, here are the six Comparison Operators in Swift:

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

Let's see how these work with a commonly-used example – a bank account.

Example 1: Bank Account

At the bottom of your Playground, add the following variables bankBalance and itemToBuy:

...

var bankBalance = 400
var itemToBuy = 100

So we have a bank account holding $400 and want to buy an item with a price of $100.

Let's use a conditional and a comparison operator to determine whether or not we can purchase the item we want.

...

var bankBalance = 400
var itemToBuy = 100

if bankBalance >= itemToBuy {
    print("Purchased item!")
}

On the right-hand side of the Playground, you should see "Purchased item!\n" print out. Don't worry about the "\n" part. That is only Xcode telling you that after our message is printed it will create a new line.

I'm sure you see how powerful and useful comparison operators are. Here is yet another example of using comparison operators. We will write some code to check if a download has completed or not.

Example 2: Download completion checker

At the bottom of your Playground, type:

...

var downloadHasFinished = false

if downloadHasFinished == true {
    print("Download complete!")
} else {
    print("Loading data...")
}

Or we could simply use the "Not Equal To" comparison operator: !=

...

var downloadHasFinished = false

if !downloadHasFinished {
    print("Download complete!")
} else {
    print("Loading data...")
}

It's okay if the code above is confusing and seems flipped from the example above it. That's because it is! But let me explain.

  1. First, we declare downloadHasFinished and set it's value to false.
  2. Then, inside of an if/else statement we type !downloadHasFinished meaning whatever value downloadHasFinished currently has, in this case false, make it NOT equal to that (invert it to true).
  3. Afterward, since the value of downloadHasFinished is now true, print "Download complete!"

The same principle can be applied to check or verify String values or any other values so long as they are of the same type.

Example 3: Book title verification

Imagine that you hired a new librarian who was always messing up the titles of books when entering them into the computer:

...

var officialBookTitle = "Harry Blotter and the Moppit of Meyer"

var attemptedEntryBookTitle = "Harry Plotter and the Muppet Mayor"

if officialBookTitle != attempedEntryBookTitle {
    print("Need to check spelling, try again.")
}

Closing thoughts

Booleans, Conditional Statements, and Comparison Operators are foundational components of programming in any language, but especially in Swift. You will use Booleans for all kinds of verification, completion handling, etc.

Wrapping up

We learned that a Boolean is a true or false value. We also learned that a conditional statement only runs code that meets a certain condition (hence the name!). Finally, we learned that the six comparison operators come in handy for comparing values of all kinds.

You rock! 🤘 Way to complete another chapter!

Exercise

Create a variable of type Bool named syncComplete and set it to false. Write a conditional statement to check whether or not syncing is complete. If syncComplete is true, print "Sync complete!". If syncComplete is false, print "Syncing...".

Create a variable and write a conditional statement that will check the balance of arcade tokens. If the balance is equal to or greater than 500, print out "Gamer Supreme!". If the balance is less than 500, print out "Child's Play...".