Chapters

Hide chapters

Swift Apprentice

Section III: Building Your Own Types

Section 3: 8 chapters
Show chapters Hide chapters

Section IV: Advanced Topics

Section 4: 10 chapters
Show chapters Hide chapters

1. Expressions, Variables & Constants
Written by Matt Galloway

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

Welcome to the book! In this first chapter, you’re going to learn a few basics. You’ll learn how code works first. Then you’ll learn about the tools you’ll be using to write Swift code.

Then, you’ll start your adventure into Swift by learning some basics such as code comments, arithmetic operations, constants and variables. These are some of the fundamental building blocks of any language, and Swift is no different.

First of all, you’ll cover the basic workings of computers, because it really pays to have a grounding before you get into more complicated aspects of programming.

How a computer works

You may not believe me when I say it, but a computer is not very smart on its own. The power of a computer comes mostly from how it’s programmed by people like you and me. If you want to successfully harness the power of a computer — and I assume you do, if you’re reading this book — it’s important to understand how computers work.

It may also surprise you to learn that computers themselves are rather simple machines. At the heart of a computer is a Central Processing Unit (CPU). This is essentially a math machine. It performs addition, subtraction, and other arithmetical operations on numbers. Everything you see when you operate your computer is all built upon a CPU crunching numbers many millions of times per second. Isn’t it amazing what can come from just numbers?

The CPU stores the numbers it acts upon in small memory units called registers. The CPU is able to read numbers into registers from the computer’s main memory, known as Random Access Memory (RAM). It’s also able to write the number stored in a register back into RAM. This allows the CPU to work with large amounts of data that wouldn’t all fit in the bank of registers.

Here is a diagram of how this works:

As the CPU pulls values from RAM into its registers, it uses those values in its math unit and stores the results back in another register.

Each time the CPU makes an addition, a subtraction, a read from RAM or a write to RAM, it’s executing a single instruction. Each computer program does its work by running thousands to millions of simple instructions. A complex computer program such as your operating system, macOS (yes, that’s a computer program too!), consists of many millions of instructions.

It’s entirely possible to write individual instructions to tell a computer what to do, but for all but the simplest programs, it would be immensely time-consuming and tedious. This is because most computer programs aim to do much more than simple math — computer programs let you surf the Internet, manipulate images, and allow you to chat with your friends.

Instead of writing individual instructions, you write source code (or just code) in a specific programming language, which in your case will be Swift. This code is put through a computer program called a compiler, which converts the code into those small machine instructions the CPU knows how to execute. Each line of code you write will turn into many instructions — some lines could end up being tens of instructions!

Representing numbers

As you know by now, numbers are a computer’s bread and butter, the fundamental basis of everything it does. Whatever information you send to the compiler will eventually become a number. For example, each character within a block of text is represented by a number. You’ll learn more about this in Chapter 2, which delves into types including strings, the computer term for a block of text.

(0 * 1000) + (4 * 100) + (2 * 10) + (3 * 1) = 423

Binary numbers

Because you’ve been trained to operate in base 10, you don’t have to think about how to read most numbers — it feels quite natural. But to a computer, base 10 is way too complicated! Computers are simple-minded, remember? They like to work with base 2.

(1 * 8) + (1 * 4) + (0 * 2) + (1 * 1) = 13
(1 * 256) + (1 * 128) + (0 * 64) + (1 * 32) + (0 * 16) + (0 * 8) + (1 * 4) + (1 * 2) + (1 * 1) = 423

Hexadecimal numbers

As you can imagine, working with binary numbers can become quite tedious, because it can take a long time to write or type them. For this reason, in computer programming, we often use another number format known as hexadecimal, or hex for short. This is base 16.

(12 * 4096) + (0 * 256) + (13 * 16) + (14 * 1) = 49374
c = 1100
0 = 0000
d = 1101
e = 1110

c0de = 1100 0000 1101 1110

How code works

Computers have a lot of constraints, and by themselves, they can only do a small number of things. The power that the computer programmer adds, through coding, is putting these small things together, in the right order, to produce something much bigger.

Step 1. Load photo from hard drive.
Step 2. Resize photo to 400 pixels wide by 300 pixels high.
Step 3. Apply sepia filter to photo.
Step 4. Print photo.

Playgrounds

The set of tools you use to write software is often referred to as the toolchain. The part of the toolchain into which you write your code is known as the Integrated Development Environment (IDE). The most commonly used IDE for Swift is called Xcode, and that’s what you’ll be using.

Creating a playground

When you open Xcode, it will greet you with the following welcome screen:

Playgrounds overview

At first glance, a playground may look like a rather fancy text editor. Well, here’s some news for you: It is essentially just that!

Getting started with Swift

Now that you know how computers work and know what this “playground” thing is, it’s time to start writing some Swift!

Code comments

The Swift compiler generates executable code from your source code. To accomplish this, it uses a detailed set of rules you will learn about in this book. Sometimes these details can obscure the big picture of why you wrote your code a certain way or even what problem you are solving. To prevent this, it’s good to document what you wrote so that the next human who passes by will be able to make sense of your work. That next human, after all, may be a future you.

// This is a comment. It is not executed.
// This is also a comment.
// Over multiple lines.
/* This is also a comment.
   Over many..
   many...
   many lines. */
/* This is a comment.
 
 /* And inside it 
 is 
 another comment.
 */
 
 Back to the first.
 */

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("Hello, Swift Apprentice reader!")

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.

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 you learned in your early school days: addition, subtraction, multiplication and division. For these simple operations, Swift uses the following operators:

2 + 6
10 - 2
2 * 4
24 / 3

2+6
2+6   // OK
2 + 6 // OK
2 +6  // ERROR
2+ 6  // ERROR

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.

22 / 7
22.0 / 7.0

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. Let’s turn to them now.

28 % 10
(28.0).truncatingRemainder(dividingBy: 10.0)

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. Then they return the decimal form of the new binary number.

1 << 3

32 >> 2

Order of operations

Of course, it’s likely that when you calculate a value, you’ll want to use multiple operators. Here’s an example of how to do this in Swift:

((8000 / (5 * 10)) - 32) >> (29 % 5)
350 / 5 + 2
350 / (5 + 2)

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 at Swift and writing those complex games!

sin(45 * Double.pi / 180)
// 0.7071067811865475

cos(135 * Double.pi / 180)
// -0.7071067811865475
(2.0).squareRoot()
// 1.414213562373095
max(5, 10)
// 10

min(-5, -10)
// -10
max((2.0).squareRoot(), 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 represent and work with this data as various types of numbers, but other times the data comes in more complex forms such as text, images and collections.

Constants

Take a look at this:

let number: Int = 10
let pi: Double = 3.14159
number = 0

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.

var variableNumber: Int = 42
variableNumber = 0
variableNumber = 1_000_000

Using meaningful names

Always try to choose meaningful names for your variables and constants. Good names act as documentation and make your code easy to read.

var 🐶💩: Int = -1

Increment and decrement

A common operation that you will need is to be able to increment or decrement a variable. In Swift, this is achieved like so:

var counter: Int = 0

counter += 1
// counter = 1

counter -= 1
// counter = 0
var counter: Int = 0
counter = counter + 1
counter = counter - 1
counter = 10

counter *= 3  // same as counter = counter * 3
// counter = 30

counter /= 2  // same as counter = counter / 2
// counter = 15

Mini-exercises

If you haven’t been following along with the code in Xcode, now’s the time to create a new playground and try some exercises to test yourself!

Challenges

Before moving on, here are some challenges to test your knowledge of variables and constants. It is best if you try to solve them yourself, but solutions are available if you get stuck. These came with the download or are available at the printed book’s source code link listed in the introduction.

Challenge 1: Variables

Declare a constant Int called myAge and set it equal to your age. Also declare an Int variable called dogs and set it equal to the number of dogs you own. Then imagine you bought a new puppy and increment the dogs variable by one.

Challenge 2: Make it compile

Given the following code:

age: Int = 16
print(age)
age = 30
print(age)

Challenge 3: Compute the answer

Consider the following code:

let x: Int = 46
let y: Int = 10
// 1
let answer1: Int = (x * 100) + y 
// 2
let answer2: Int = (x * 100) + (y * 100)  
// 3
let answer3: Int = (x * 100) + (y / 10)

Challenge 4: Add parentheses

Add as many parentheses to the following calculation, ensuring that it doesn’t change the result of the calculation.

8 - 4 * 2 + 6 / 3 * 4

Challenge 5: Average rating

Declare three constants called rating1, rating2 and rating3 of type Double and assign each a value. Calculate the average of the three and store the result in a constant named averageRating.

Challenge 6: Electrical power

The power of an electrical appliance can be calculated by multiplying the voltage by the current. Declare a constant named voltage of type Double and assign it a value. Then declare a constant called current of type Double and assign it a value. Finally calculate the power of the electrical appliance you’ve just created storing it in a constant called power of type Double.

Challenge 7: Electrical resistance

The resistance of such an appliance can be then calculated (in a long-winded way) as the power divided by the current squared. Calculate the resistance and store it in a constant called resistance of type Double.

Challenge 8: Random integer

You can create a random integer number by using the function arc4random(). This creates a number anywhere between 0 and 4294967295. You can use the modulo operator to truncate this random number to whatever range you want. Declare a constant randomNumber and assign it a random number generated with arc4random(). Then calculate a constant called diceRoll and use the random number you just found to create a random number between 1 and 6.

Challenge 9: Quadratic equations

A quadratic equation is something of the form a⋅x² + b⋅x + c = 0. The values of x which satisfy this can be solved by using the equation x = (-b ± sqrt(b² - 4⋅a⋅c)) / (2⋅a). Declare three constants named a, b and c of type Double. Then calculate the two values for x using the equation above (noting that the ± means plus or minus — so one value of x for each). Store the results in constants called root1 and root2 of type Double.

Key points

  • Add: +
    Subtract: -
    Multiply: *
    Divide: /
    Remainder: %
    
  • Add and assign: +=
    Subtract and assign: -=
    Multiply and assign: *=
    Divide and assign: /=
    
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2023 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.

Unlock now