Overview

3 Your First Real Swift Code Using Variables!

This chapter moves from simple Playground printouts to “real” Swift by introducing variables—named places in memory that let apps remember and update information. You see why apps track changing values like scores or levels, why descriptive names beat single letters, and how variables can hold different kinds of data. A quick tour of core types—integers, decimals, booleans, and strings—highlights that numbers support math while text does not, so “four” and 4 are very different to Swift.

You practice declaring variables with var, sometimes stating the type explicitly and other times letting Swift infer it, all while following naming rules. The chapter covers optionals for “not yet known” values, printing and “spying” on data, and embedding values in text using string interpolation. It shows updating variables after creation, concatenating strings versus adding numbers, and converting between String, Int, and Decimal so user-entered text can be used in calculations, along with what happens when a conversion doesn’t make sense.

Math in Swift starts with the basic operators (+, −, ×, ÷) and the important gotcha that integer division drops the fractional part, so you’ll use decimals when you need precise results. You then step up to square root, exponentiation, and modulus for remainders, applying operations both inside print statements and when assigning to variables. Through small Playground exercises, you format output, combine and transform data, and build the habits needed to progress from Playgrounds to full apps.

This shows two variables stored in the computer’s memory. One is a variable named age, with the value 12 stored in the computer’s memory, and the other variable is called name, with the value “Frank” saved in the computer’s memory.
This is how the Playground will let tell you that you broke a variable naming rule.
This is what your playground will look like after you type in the code in listing 3.1.
Notice when you don’t use the \ and () to format your text output, Swift doesn’t print the values of your variables.
Converting strings and integers in the playground.
Using an operator with numbers in the Playground.
Doing math in the Playground.
Advanced math in the playground

   Check your App-Knowledge

  1. What arevariables?
  2. What’s it called when you put two strings together?
  3. Why is a variablecalled a variable?
  4. What does data conversion mean?
  5. Why might you need to convert data?
  6. Write code to declare variables that hold these pieces of data:
    “That pizza was so good!”
    17
    2.23
    “15.49”
  7. What will the output be from the following commands? (HINT: Some of them won’t work, can you figure out what’s causing the errors?)
  1. Assume there are two variables var1 and var2 of type String with values “13” and “25” respectively. Write the code to print the following using only the two variables and print(). The sum should be calculated.
    13+25=38
  2. Assume there are two variables var3 and var4 of type String with values “15” and “4” respectively. Write the code to print the following using only the two variables and print(). The remainder should be calculated.
    If you divide 15 by 4, you get a remainder of 3.

FAQ

What is a variable in Swift and why do apps need them?A variable is a named place in memory that can hold a value that may change over time. Apps use variables to remember information like scores, ages, levels, names, and more, so they can read or update it later as the app runs.
How do I declare a variable and give it a value?Use var with an optional type annotation. Examples: var someonesAge: Int = 23 and var myAge = 11. In the second case Swift infers the type from the value.
How do I declare a variable when I don’t have a value yet?Use an Optional type. Example: var someonesAge: Int! lets you create it without an initial value and assign later (e.g., someonesAge = 12). Don’t read it before you assign a real value.
What are the most common data types I’ll use?- Int for whole numbers (…, -2, -1, 0, 1, 2, …)
- Decimal for decimal numbers (e.g., 3.14, 7.5)
- Bool for true/false
- String for text (e.g., "Anne")
You can do math with numbers, not with text.
What are the rules for naming variables?Names must start with a letter or underscore, contain no spaces, and avoid special characters like %, $, &, *. They cannot start with a digit. Examples: ageOfUser (good), User Name (bad), 5thFile (bad).
How do I show a variable’s value in output?Use print() and string interpolation: print("Age is \(age)"). In a Playground, typing the variable name also shows its value in the sidebar.
What is string concatenation and how is it different from addition?Concatenation joins strings with + (e.g., "ro" + "bot" = "robot"). With numbers, + performs arithmetic (e.g., 5 + 5 = 10). You can’t use -, *, or / with strings, and you can’t mix strings and numbers without converting types.
How do I convert between Strings and numbers?Convert before doing math. Example: let int1 = Int("12")! converts a String to an Int; then int1 + 3 works. If a conversion can’t succeed (e.g., "Fred"), a forced unwrap (!) will crash—use valid numeric text or handle optionals safely.
Why does 15 / 2 print 7 instead of 7.5, and how do I get a decimal result?15 and 2 are Ints, so Int division drops the decimal part (no rounding). Use decimal types or literals: 15.0 / 2.0 gives 7.5.
What math operators and functions can I use?Basic: +, -, *, / for arithmetic; % for modulus (remainder). Functions: sqrt(9.0) gives 3.0, pow(5.0, 3.0) gives 125.0. Choose the right types (Int vs Decimal) to get the results you expect.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hello Swift! ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hello Swift! ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hello Swift! ebook for free