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?
Printing Out
It’s also useful to see the results of what your code is doing. In Swift, you can achieve this through the use of the print
command.
print
will output whatever you want to the debug area, which is sometimes referred to as the console.
For example, consider the following code:
print("Hello, Swift Apprentice reader!")
This will output a nice message to the debug area, like so:
You can hide or show the debug area using the downward-arrow-in-a-box button highlighted in red in the image above. You can also click View ▸ Debug Area ▸ Show Debug Area in the menu bar to do the same thing.
Arithmetic Operations
When you take one or more pieces of data and turn them into another piece of data, this is known as an operation.
The simplest way to understand operations is to think about arithmetic. The addition operation takes two numbers and converts them into the sum of the two numbers. The subtraction operation takes two numbers and converts them into the difference of the two numbers.
You’ll find simple arithmetic all over your apps: From tallying the number of “likes” on a post to calculating the correct size and position of a button or a window, numbers are indeed everywhere!
In this section, you’ll learn about the various arithmetic operations that Swift has to offer by considering how they apply to numbers. Later, you’ll see operations for types other than numbers.
Simple Operations
All operations in Swift use a symbol known as the operator to denote the type of operation they perform.
Consider the four arithmetic operations that you learned in your early school days: addition, subtraction, multiplication and division. For these simple operations, Swift uses the following operators:
-
Add:
+
-
Subtract:
-
-
Multiply:
*
-
Divide:
/
These operators are used like so:
2 + 6
10 - 2
2 * 4
24 / 3
Each of these lines is what is known as an expression. An expression has a value. In these cases, all four expressions have the same value: 8. You write the code to perform these arithmetic operations much as you would write it if you were using pen and paper.
In your playground, you can see the values of these expressions in the right-hand bar, known as the results sidebar, like so:
If you want, you can remove the whitespace surrounding the operator:
2+6
Removing the whitespace is an all-or-nothing thing: You can’t mix styles. For example:
2+6 // OK
2 + 6 // OK
2 +6 // ERROR
2+ 6 // ERROR
It’s often easier to read expressions if you have whitespace on either side of the operator.
Decimal Numbers
All of the operations above have used whole numbers, more formally known as integers. However, as you will know, not every number is whole.
As an example, consider the following:
22 / 7
This, you may be surprised to know, results in the number 3. This is because, if you only use integers in your expression, Swift makes the result an integer. In this case, the result is rounded down to the next integer.
You can tell Swift to use decimal numbers by changing it to the following:
22.0 / 7.0
This time, the result is 3.142857142857143, as expected.
The Remainder Operation
The four operations you’ve seen so far are easy to understand because you’ve been doing them for most of your life. Swift also has more complex operations you can use, all of them standard mathematical operations — just less common ones. You’ll review them, now.
The first of these is the remainder operation, also called the modulo operation. In division, the denominator goes into the numerator a whole number of times, plus a remainder. This remainder is exactly what the remainder operation gives. For example, 10 modulo 3 equals 1, because 3 goes into 10 three times, with a remainder of 1.
In Swift, the remainder operator is the %
symbol, and you use it like so:
28 % 10
In this case, the result equals 8
, because 10 goes into 28 twice with a remainder of 8. If you want to compute the same thing using decimal numbers, you do it like so:
(28.0).truncatingRemainder(dividingBy: 10.0)
This computes divides 28 by 10 and then truncates the result, chopping off any extra decimals, and it returns the remainder of that. The result is identical to % when there are no decimals.
Shift Operations
The shift-left and shift-right operations take the binary form of a decimal number and shift the digits left or right, respectively. They then return the decimal form of the new binary number.
For example, the decimal number 14 in binary, padded to 8 digits, is 00001110
. Shifting this left by two places results in 00111000
, which is 56 in decimal.
Here’s an illustration of what happens during this shift operation:
The digits that come in to fill the empty spots on the right become 0. The digits that fall off the end on the left are lost.
Shifting right is the same, but the digits move to the right.
The operators for these two operations are as follows:
-
Shift left:
<<
-
Shift right:
>>
These are the first operators you’ve seen that contain more than one character. Operators can contain any number of characters, in fact.
Here’s an example that uses both of these operators:
1 << 3
32 >> 2
Both of these values equal the number 8.
One reason for using shifts is to make multiplying or dividing by powers of two easy. Notice that shifting left by one is the same as multiplying by two, shifting left by two is the same as multiplying by four, and so on. Likewise, shifting right by one is the same as dividing by two, shifting right by two is the same as dividing by four, and so on.
In the old days, code often made use of this trick because shifting bits is much simpler for a CPU to do than complex multiplication and division arithmetic. Therefore, the code was faster if it used shifting. However, these days, CPUs are much faster and compilers can even convert multiplication and division by powers of two into shifts for you. So you’ll see shifting only for binary twiddling, which you probably won’t see unless you become an embedded systems programmer!