Chapter 3: Programming & Variables

In this exciting chapter, we are going to talk about variables, operators, and a little bit about how computers work. This is not a theoretical book, but I do want you to understand some of the basic principles that are happening underneath the hood so that you can have a foundation to build upon.


What you will learn

  • Creating your first variable
  • Unary, Binary, and Ternary Operators
  • Another variable example

Key Terms

  • Variable: A container used in programming to store a value of some type.
  • String: A stored value consisting of characters or words.
  • Boolean: A stored value consisting of a true or false property.

Variables are used in programming to store information which can be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name so that our programs can be understood more clearly by other programmers and ourselves. If it's helpful, think of a variable as a container that holds information, their sole purpose is to label and store data in memory which can later be used in your program. This is a basic flyover of what a variable is and how it works, but now you will create some variables in Xcode to help you understand how they work in the context of software development.

Creating your first variable

First, open Xcode if you haven't already and click Create New Playground. Give it a name like Variables, 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 1.3.1.

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

Playgrounds in Xcode are an amazing way to test code snippets to see if and how your code works. It's also a great way for me as an instructor to teach you basic coding principles in Swift.

By default, the Playground we just created already contains a variable. Figure 1.3.1 shows the code below.

var str = "Hello, playground"

Wherever you see var, that's short for variable. You're telling your computer that you want to create a variable (a container that you want to put data into). We can name it whatever we want for the most part, but some names are not allowed. For instance, we can't put numbers in front of a variable name (i.e. "2WeeksPay"), but you can use words first and then numbers (i.e. "day1").

var

In this case, let's use message as our variable's name. Variables should always be descriptive and should tell you what's being stored in them.

var message

To give our variable a value, we need to use an equals sign just like in any math equation to show that our variable is equal to something.

var message =

We are storing some words in our variable, and the name for this is a String. To declare a String, you must use double quotes like so:

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

The key term for what we have written in code here is String Literal because we have given our String an inherent value. Later on, we will see how a String can be created with an empty value or no value at all.

Let's change the value of our variable message to be "Hello, playground".

This is your first variable. The data type is a String, made up of characters and words. That information will be stored in the variable.

Under the hood, this program is running on our mac, so it's actually being stored in the memory on the computer somewhere which is pretty cool! All of this is happening for us automatically.

So, in review we created a variable by specifying var, gave it a descriptive name, and then we gave it a String value of, "Hello, playground".

Variables can be changed as many times as you want. The data stored inside of them can change as our app needs it to. We will talk about this more later on when we compare it with a Constant.

Unary, Binary, and Ternary Operators

For a moment, let's talk about Operators. There are 3 types of Operators in Swift – unary, binary, and ternary. But what the heck do these words mean?

Unary operators only only affect one target.

For example, you can create a Boolean (true/false value) which is called amICool:

var amICool = true

Based on the code above, I am definitely cool. 😎

Then say a new fad or trend comes out that I haven't started yet... So now I'm "uncool". Well, now we can use a unary prefix operator to change that:

var amICool = true
amICool = !amICool

A unary operator basically inverts the value of amICool, our variable. Now amICool is false because it is the opposite of amICool. Sadly, I'm no longer cool because I didn't follow the new fad or trend. 😭

Unary operators affect one target, but binary operates on two targets.

Binary operators operate on two targets.

They are seen regularly throughout code as most variables and constants rely on another value to do their work. Here are some examples:

var accountBalance = 9.00
var isBatmanAmazing = true
var officialJobDescription = "Mad Scientist & Rare Cheese Connoisseur"

All of the above lines of code operate on two targets – the variable name (i.e. isBatmanAmazing) and the value following the equals sign (i.e. true).

Ternary operators affect three targets.

Now we are going to add another variable called feelGoodAboutMyself and set it's value to true.

var feelGoodAboutMyself = true

That's a variable and it's of type Boolean. We are storing the value true into this variable. Now let's use a ternary operator just for fun.

var feelGoodAboutMyself = true
feelGoodAboutMyself = amICool ? true : false

In a ternary operator, the question mark symbol (?) means "if" and the colon symbol ( : ) means "otherwise".

The code above means that if the value of amICool is true, then feelGoodAboutMyself should be set to true, otherwise it should be set to false.

It's a ternary operator because it works on 3 targets – amICool, true, and false.


Helpful Tip: When you're programming, you're not going to use these terms, but if you're in an interview, they might ask you to define them, so they're good to know about!


Another variable example

In your Playground file, create a variable called bankAccountBalance and set it to equal 100.

var bankAccountBalance = 100

Next, create a variable named cashRegisterMessage. We want to have a message that will print out for someone who wants to buy something at a store.

var bankAccountBalance = 100
var cashRegisterMessage = "You are broke as a joke."

Now create a variable named itemPrice and set it's value to 60.

var bankAccountBalance = 100
var cashRegisterMessage = "You are broke as a joke."
var itemPrice = 60

We're also going to write a ternary operator to check if our bank account balance is greater than or equal to 50. If the operator returns true, then you are able to buy the item, otherwise, you can't buy the item because you are broke.

var bankAccountBalance = 100
var cashRegisterMessage = "You are broke as a joke."
var itemPrice = 60

bankAccountBalance >= itemPrice ? "Item purchased!" : cashRegisterMessage

Now, change the price of the item to 150 and add in the following conditional if/else statement (more on these in a following chapter).

var bankAccountBalance = 100
var cashRegisterMessage = "You are broke as a joke."
var itemPrice = 150

if bankAccountBalance >= itemPrice {
    cashRegisterMessage = "Item purchased!"
    print(cashRegisterMessage)
} else {
    print(cashRegisterMessage)
}

What do you notice changed in the console output on the right-hand side of your Playground window? "You are now broke as a joke."

The if/else code above means that if the value of bankAccountBalance is greater than or equal to the itemPrice, then cashRegisterMessage should be set to "Item purchased!", otherwise it should be set to the default message we set.

There are other operators that we'll learn about later such as math operators for adding, subtracting, multiplying, and dividing. There is even a remainder operator for doing division and getting only the remainder of the result. We will talk more about those later.

Wrapping up

This chapter was a flyover of how variables work and what a variable is. We talked about unary operators, binary operators, and ternary operators. You learned that you can create a container called a variable by starting with the keyword var and giving the container a descriptive name like bankAccountBalance.

You learned that you can store a value into that container such as a string (text), boolean (true/false), or even a number (integers/decimals). You can assign the value using the assignment operator (equals sign).

Finally, I want to encourage you to dig more into this! Search online for the three types of operators and look up what a variable is. It's important to know these things because you want to become a great programmer!

Exercise

Create 4 variables to hold these types of data:

  • Your name (String)
  • Your age (Int)
  • The temperature in your location (Double)
  • Something that is true about yourself (Bool)