Chapter 4. Favorite Things

This chapter will introduce you to the concept of variables and constants. It will cover how we use them to manage state in an iOS application. We will take what you've learned in the last chapter in working with print statements and build upon that to help you understand the problem that is solved using variables and constants.

The topics this chapter covers are as follows:

  • Creating variables and constants
  • Assigning a value to a variable
  • Reading a value from a variable

Variables and constants

What's your favorite Disney song? Our is A Whole New World from Aladdin. What's your favorite ice cream flavor? For us, nothing beats vanilla. If we wanted to print out some of our favorite items in a playground file, we know how to do that!

Create a new playground file and name it FavoriteThings, as illustrated. Save it wherever you like; we recommend saving all of this work in a place you can remember. That way, you can access it easily when you need to reference it later on:

Variables and constants

Clear out all the code that a newly created playground file provides to you; that way, you're left with a completely blank file:

Variables and constants

We mentioned earlier that our favorite Disney song is A Whole New World. We also mentioned that our favorite ice cream flavor is vanilla. Let's pretend, for a second, that your best friend just asked you those questions. Instead of speaking to them, you decide to write some Swift code (because you're an awesome developer) and show them what prints to the console.

We can do this with the following lines of code:

print("My favorite Disney song is A Whole New World.")
print("My favorite ice-cream flavor is Vanilla")

Tip

All related source code for this chapter can be found here: https://github.com/swift-book-projects/swift-3-programming-for-kids/tree/master/Chapter-4

This is how your playground file should look if you're getting along:

Variables and constants

Now, our best friend knows what our favorite Disney song and ice cream flavor is. A few days later, our favorite uncle asks us the exact same question. So, we create a new print statement letting uncle Carl know as we show off our new Swift skills:

print("Hi Uncle Carl, my favorite Disney song is A Whole New World. Also, my favorite ice-cream flavor is Vanilla")

Last but not least, our mother asks us the exact same question. So, we provide a print statement for her as well!

print("Hi Mom! <3 you. My favorite Disney song is A Whole New World. My favorite ice-cream flavor is Vanilla.")

As of now, your playground file should look like this:

Variables and constants

After feeling really proud about communicating to our friends and family through Swift code, our sister decides to burst our bubble. She takes a look at our application and asks us to change our favorite Disney song to Let It Go. Also, she asks us to change our favorite ice cream flavor to strawberry. After arguing about it for 30 minutes, we agree with her decision.

This leaves us with an annoying task. We now have to go through all of our code and manually change these items to reflect our new decision. So, let's do that.

On second thought, let's not do that. That's a lot of work, there has to be a better way. Is there a better way? Yes!

Variables

Imagine if we had the ability to store our favorite things in separate boxes (to help us remember). To help us organize and know what's inside each box, we will label them. If we want to find out what our favorite ice cream flavor is, we will go up to our boxes and look for the one labeled Favorite Ice Cream. After opening the box, we will see a piece of paper with the word Vanilla on it inside.

Can we do something like this in code? Yes, we can do it with variables. You can think of variables as containers (boxes) that hold information. Their sole purpose is to label and store information:

var favoriteIceCream = "Strawberry"

The preceding code is how we've created a new variable, called favoriteIceCream and gave it a value of Strawberry.

The variable favoriteIceCream represents our labeled box and Strawberry represents the piece of paper inside the box, letting us know what our favorite ice cream flavor is.

Here, var is what's known as a keyword. The var keyword being used here means variable. In order to create a variable in Swift, you have to preface the name of your variable with the var keyword. We've decided to call our variable favoriteIceCream. Why? This is because it's holding on to the value Strawberry. It represents what our favorite ice cream flavor is.

When you name your variables (label your boxes) in Swift, you should do so using the following technique. The first letter of your variable should always be lowercase. Every other word should be uppercase.

With this new found knowledge, try to create a new variable, called favoriteDisneySong, and give it a value of Let It Go without looking at the answer.

How did you do? Here's the answer:

var favoriteDisneySong = "Let It Go"

Arrange your playground file so that it looks like this:

Variables

In the future chapters, we will discuss in detail as to what string interpolation is. For now, we will just use it-but first, we will give you a brief explanation as to what it is. String interpolation is the ability to replace any variable with its String value within the creation of another String value.

For example, if you replace the code on line 6 with the following, take a look at what is printed in the console:

Input:

print("My favorite Disney song is (favoriteDisneySong)")

Output:

My favorite Disney song is Let It Go

Interesting! The code is able to open up our box labeled favoriteDisneySong and replace it with the string Let It Go. That's what is known as string interpolation. You have to add a back slash  followed by two parentheses ( ). You have to put the name of your variable within these parentheses. Swift is then able to replace that variable with its value. The variable is favoriteDisneySong and its value is Let It Go.

Let's replace some of our code in the playground file to take advantage of using string interpolation. Before looking at the answer, see if you can replace all the places where you wrote out your favorite Disney song and your favorite ice cream with the variable instead:

Variables

Look how easy it is now to change our favorite ice cream flavor and Disney song! We can change it in one place, and as soon as we make the change, our best friend, uncle Carl, and our mom are able to see the new results, without us having to manually change it everywhere.

Go ahead and try it some more! Change the variables to reflect your own favorite Disney song and ice cream flavor.

Constants

Create a new playground file and name it Constants. After doing so, clear all of its contents so that you're left with a blank slate.

Here's a quick challenge. Create a variable, called favoriteColor, and assign it a value that represents your favorite color. Our favorite color is green, so we will solve this problem as shown:

var favoriteColor = "Green"

On the next line, let's assign a different value to this favoriteColor variable:

favoriteColor = "Blue"

Your playground file should look something like this (depending on what colors you choose):

Constants

What if we were to print our favoriteColor variable. What would print out to the console? Let's try it out! Add this line of code where you changed the favoriteColor variable to Blue:

print(favoriteColor)

Well, look at that, Blue prints out to the console. This means we can change our variables throughout our application. The latest change that is made is the one that sticks:

Constants

There will be times, though, when you will want to create a variable that should never be allowed to change. For instance, Jim's mother's name is Maryann. If we created a variable called momsName, we want to be able to assign it the value Maryann and ensure that it never changes. We can do this using what are known as constants in Swift. A constant is a variable that allows you to assign it a value only once!

let momsName = "Maryann"

The preceding code is how you create a constant, it's that simple! Can you spot the difference between creating a variable and creating a constant? The only difference is that we're using the let keyword instead of the var keyword. If we try assigning a new value to momsName, we will be met with an error. Let's try assigning the value Patty to our momsName constant to see the error Xcode produces:

Constants

The code in the preceding screenshot is: 

momsName = "Patty"

The error message that is provided is very informative:

Constants

It's telling us that we can't assign a value to momsName because it's a let constant. That's great, it's exactly what we want! Throughout our entire application, momsName is guaranteed to have the value Maryann. There's no way that it can be any other value; this serves as a great tool and allows us to write very safe code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.239.148