Lesson 2 – Storing and Combining Values with Constants, Variables, and Operators
Perform arithmetical calculations with basic operators
Now that you know how to write a program, it’s time to do something more than just print a message to the console. Let’s start with numbers and operations.
I know, exciting.
I can hear you already saying: “Who cares about numbers? Give me the real stuff!” You are learning programming to create cool apps, and arithmetic isn’t cool.
But bear with me.
The reality is that numbers are everywhere in apps. Want to create a banking app? Money is made of numbers. To-do lists and grocery lists? Count how many items are completed. Social networks display the number of likes and shares, and so on.
So, let’s have a look and get over this quickly.
Swift has five arithmetic operations: addition, subtraction, multiplication, division, and modulo (which is the remainder of a division. It might seem odd, but I promise it will be helpful).
1 2 3 4 5 |
3 + 4 // 7 17 - 4 // 13 6 * 8 // 48 25 / 5 // 5 17 % 7 // 3 |
Time to have a quick look at some useful terminology.
The operation symbols in the above code are called operators. Swift has several of these, and we will cover the most useful ones in this course. The language also works with custom operators, but that’s an advanced feature.
Arithmetical operations in Swift have the expected precedence from Maths, i.e., multiplication comes before addition and so on. Use parentheses as in Maths for operations with higher priority.
1 2 |
1 + 2 * 3 // 7 (1 + 2) * 3 // 9 |
Use let constants to give understandable names to values
Time to use basic operations to write a program that does more than simple calculations.
Imagine a list of groceries with no final price.
1 |
6 * 3 + 1 * 17 + 2 * 2 // 39 |
The above code computes the groceries’ total price, but what do those numbers mean exactly?
Use constants to name things in Swift.
1 2 3 4 5 6 7 |
let cartonsOfMilk = 6 let priceOfMilk = 3 let kilosOfBeef = 1 let priceOfBeef = 17 let kilosOfApples = 2 let priceOfApples = 2 let total = cartonsOfMilk * priceOfMilk + kilosOfBeef * priceOfBeef + kilosOfApples * priceOfApples // 39 |
Run the program to see the value of each constant.
The let
keyword defines a constant in Swift. Keywords are words reserved for the language that can’t be used as names of other things.
The =
symbol is called the assignment operator because it assigns a value to a constant. It’s not the same as the equals symbol in Maths which says that two things are equal (There is another operator for that, more on it later).
Use variables to store partial and temporary values
Constants never change their values after they get assigned. This means they can’t store partial totals for the grocery list’s added items.
1 2 3 4 5 6 7 8 9 10 |
var total = 0 let cartonsOfMilk = 6 let priceOfMilk = 3 total += cartonsOfMilk * priceOfMilk // 18 let kilosOfBeef = 1 let priceOfBeef = 17 total += kilosOfBeef * priceOfBeef // 35 let kilosOfApples = 2 let priceOfApples = 2 total += kilosOfApples * priceOfApples // 39 |
The var
keyword defines a variable in Swift. Variables can change their values.
The +=
operator is called addition assignment operator. It’s a compound operator because it performs two operations at the same time:
- Add the new value to the current value of the
total
variable. - Assign the result to the variable.
Swift also has compound operators for the other arithmetic operations: - =
, *=
, /=
, and %=
.
These are syntactic sugar, i.e., language features that make life easier. The partial totals can also be computed separately using the assignment and addition operators.
1 2 3 4 5 6 7 8 9 10 |
var total = 0 let cartonsOfMilk = 6 let priceOfMilk = 3 total = total + cartonsOfMilk * priceOfMilk // 18 let kilosOfBeef = 1 let priceOfBeef = 17 total = total + kilosOfBeef * priceOfBeef // 35 let kilosOfApples = 2 let priceOfApples = 2 total = total + kilosOfApples * priceOfApples // 39 |
We can also store the partial totals into separate constants in case they are needed later.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var total = 0 let cartonsOfMilk = 6 let priceOfMilk = 3 let totalMilk = cartonsOfMilk * priceOfMilk // 18 total += totalMilk // 18 let kilosOfBeef = 1 let priceOfBeef = 17 let totalBeef = kilosOfBeef * priceOfBeef // 17 total += totalBeef // 35 let kilosOfApples = 2 let priceOfApples = 2 let totalApples = kilosOfApples * priceOfApples // 4 total += totalApples // 39 |
It’s easy to make mistakes when updating variables that should not change. Use constants as much as possible and switch to variables only when needed.
Name things so that programs are easy to read for you and others
Swift has some restrictions for names of constants and variables:
- They can’t contain mathematical symbols.
- They can’t contain spaces.
- They can’t begin with a number.
Constants and variables can have any name as long the above rules are followed. That doesn’t mean you can use any language, strange characters, or emojis.
Think about this quote during your programming career:
Programs are meant to be read by humans and only incidentally for computers to execute. – Donald Knuth
It’s essential to write easy-to-read code to understand what it does. There are a few conventions that are good to follow, even if the compiler does not enforce them:
- Name things in English. This makes it easier to share code with other developers.
- Name constants and variables using camelcase, starting with a lowercase letter.
Throughout this course, I will highlight more conventions to keep code readable. Check out a helpful summary in the Swift API Design Guidelines.
Register to get more exclusive free content
You can follow the entire course for free, with no registration required. Creating a free account gives you these extra benefits:
- Enroll in the course and track your progress;
- Download a free Swift cheat sheet;
- Get access to other exclusive guides and courses available only to registered users.
Already have an account? Login here