Chapter 3. Your first real Swift code using variables

 

Next up: variables! You’re about to take a close-up look at variables. You’ll learn what they are, why you need them, and how to use them in your programs.

This chapter covers

  • How to make your program remember something
  • What the different types of data are and why they’re required
  • How to convert one type of data to another
  • How to do math in a program

You’re all set to cover your third milestone: writing your first real Swift code by using variables. By now, you may be thinking that this whole programming business is a breeze. You’ve used the Swift Playground, and you’ve used the print() function to output words on the screen. You’ve created a playground by adding a line or two of code. Things are about to get not so simple, but they’ll be interesting and a lot of fun! In this chapter, you learn about using variables and doing math in your apps.

Apps store data in variables

In programming, you sometimes need to store data. Suppose that you need to save the names, email addresses, and phone numbers of 50 of your friends because you can’t easily remember all of them. If you write an app that can store this information, you can use it to look up the information. You can even change this data if you need to (if someone gets a new phone number, for example).

What is a variable?

Look at this equation:

x = 4

If I asked you what x is, you would (I hope) say 4. Here, x is a variable, and its value at present is equal to 4.

Declaring variables and changing values

Transforming your data

Math Operation Theater

Check your app knowledge