Swift Tutorial Part 1: Expressions, Variables and Constants
Welcome to our mini-series on getting started with programming in Swift! In this series, you’ll learn some Swift programming basics using playgrounds. By Lorenzo Boaro.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Swift Tutorial Part 1: Expressions, Variables and Constants
30 mins
- Getting Started
- Creating a Playground
- Playgrounds Overview
- Code Comments
- Printing Out
- Arithmetic Operations
- Simple Operations
- Decimal Numbers
- The Remainder Operation
- Shift Operations
- Order of Operations
- Math Functions
- Naming Data
- Constants
- Variables
- Using Meaningful Names
- Increment and Decrement
- Where to Go From Here?
Order of Operations
There are many times that it is necessary to use multiple operators to calculate a value. Here’s an example of how to do this in Swift:
((8000 / (5 * 10)) - 32) >> (29 % 5)
Notice the use of parentheses, which, in Swift, serve two purposes: to make it clear to anyone reading the code — including yourself — what you meant, and to disambiguate. For example, consider the following:
350 / 5 + 2
Does this equal 72 (350 divided by 5, plus 2) or 50 (350 divided by 7)? Those of you who paid attention in school will be screaming “72!” And you would be right!
Swift uses the same reasoning and achieves this through what’s known as operator precedence. The division operator (/
) has a higher precedence than the addition operator (+
), so, in this example, the code executes the division operation first.
If you wanted Swift to do the addition first — that is, to return 50 — then you could use parentheses like so:
350 / (5 + 2)
The precedence rules follow the same that you learned in math class at school. Multiply and divide have the same precedence, higher than add and subtract, which also have equal precedence.
Math Functions
Swift also has a vast range of math functions for you to use when necessary. You never know when you need to pull out some trigonometry, especially when you’re a pro Swifter and writing those complex games!
import
statement that comes as part of the playground template or Xcode will tell you it can’t find these functions.
For example, consider the following:
sin(45 * Double.pi / 180)
// 0.7071067811865475
cos(135 * Double.pi / 180)
// -0.7071067811865475
These compute the sine and cosine, respectively. Notice how both make use of Double.pi
, which is a constant Swift provides you, ready-made with pi, calculated to as much precision as is possible by the computer. Neat!
Then there’s this:
(2.0).squareRoot() // Same as sqrt(2)
// 1.414213562373095
This computes the square root of 2. Did you know that sin(45°) equals 1 over the square root of 2?
Another common operation is to find the max of two variables. You can use them like so:
max(5, 10)
// 10
min(-5, -10)
// -10
These compute the maximum and minimum of two numbers respectively.
If you’re particularly adventurous, you can even combine these functions like so:
max(sqrt(2), Double.pi / 2)
// 1.570796326794897
Naming Data
At its simplest, computer programming is all about manipulating data. Remember, everything you see on your screen can be reduced to numbers that you send to the CPU. Sometimes, you yourself represent and work with this data as various types of numbers; other times, the data comes in more complex forms such as text, images and collections.
In your Swift code, you can give each piece of data a name that you use to refer to it later. The name carries with it an associated type that denotes what sort of data the name refers to, such as text, numbers or a date.
You’ll learn about some of the basic types next, and you’ll encounter many other types throughout the rest of this series.
Constants
Take a look at this:
let number: Int = 10
This declares a constant called number
, which is of type Int
. Then, it sets the value of the constant to the number 10
.
=
, is known as the assignment operator.
The type Int
can store integers. The way you store decimal numbers is like so:
let pi: Double = 3.14159
This is similar to the Int
constant, except the name and the type are different. This time, the constant is a Double
, a type that can store decimals with high precision.
There’s also a type called Float
, short for floating point, that stores decimals with lower precision than Double
. In fact, Double
has about double the precision of Float
, which is why it’s called Double
in the first place. A Float
takes up less memory than a Double
but, generally, memory use for numbers isn’t a huge issue and you’ll see Double
used in most places.
Once you’ve declared a constant, you can’t change its data. For example, consider the following code:
let number: Int = 10
number = 0
This code produces an error:
Cannot assign to value: 'number' is a 'let' constant
In Xcode, you would see the error represented this way:
Constants are useful for values that aren’t going to change. For example, if you were modeling an airplane and needed to keep track of the total number of seats available, you could use a constant.
You might even use a constant for something like a person’s age. Even though their age will change with each birthday, you might only be concerned with their age at this particular instant.
Variables
Often, you want to change the data behind a name. For example, if you were keeping track of your bank account balance with deposits and withdrawals, you might use a variable rather than a constant.
If your program’s data never changed, then it would be a rather boring program! But, as you’ve seen, it’s not possible to change the data behind a constant.
When you know you’ll need to change some data, you should use a variable to represent that data instead of a constant. You declare a variable in a similar way, like so:
var variableNumber: Int = 42
Only the first part of the statement is different: You declare constants using let
, whereas you declare variables using var
.
Once you’ve declared a variable, you’re free to change it to whatever you wish, as long as the type remains the same. For example, to change the variable declared above, you could do this:
variableNumber = 0
variableNumber = 1_000_000
To change a variable, you simply assign it a new value.
This is a good time to take a closer look at the results sidebar of the playground. When you type the code above into a playground, you’ll see that the results sidebar on the right shows the current value of variableNumber
at each line:
The results sidebar will show a relevant result for each line if one exists. In the case of a variable or constant, the result will be the new value, whether you’ve just declared a constant, or if you've declared or reassigned a variable.