Chapters

Hide chapters

Swift Apprentice: Fundamentals

First Edition · iOS 16 · Swift 5.7 · Xcode 14.2

Section III: Building Your Own Types

Section 3: 9 chapters
Show chapters Hide chapters

1. Expressions, Variables & Constants
Written by Matt Galloway

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 use to write Swift code.

You’ll then 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, you’ll cover the basic workings of computers because it 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 people like you and me program it. If you want to harness the power of a computer successfully — 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 component is essentially a math machine. It performs addition, subtraction, and other arithmetical operations on numbers. Everything you see when you operate your computer is 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 can read numbers into registers from the computer’s main memory, known as Random Access Memory (RAM). It can also write the number stored in a register back into RAM. This capability 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:

Math Unit CPU Registers RAM

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 millions of instructions.

It’s entirely possible to write individual instructions to tell a computer what to do, but it would be immensely time-consuming and tedious for all but the simplest programs. After all, most computer programs aim to do much more than simple math — computer programs let you surf the Internet, manipulate images, and 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, “Types & Operations”, which delves into types, including strings, the computer term for a text block.

Images are no exception. In a computer, each image is also represented by a series of numbers. An image consists of thousands or millions of picture elements called pixels, where each pixel is a solid color. If you look closely at your computer screen, you can make out these blocks. That is unless you have a particularly high-resolution display with incredibly small pixels! Each of these solid color pixels is usually represented by three numbers: one for the amount of red, one for the amount of green and one for the amount of blue. For example, an entirely red pixel would be 100% red, 0% green and 0% blue.

The numbers the CPU works with are notably different from those you are used to. When dealing with numbers in day-to-day life, you work with them in base 10, otherwise known as the decimal system. Having used this numerical system for so long, you intuitively understand how it works. So that you can appreciate the CPU’s point of view, consider how base 10 works.

The decimal or base 10 number 423 contains three units, two tens and four hundreds:

0 4 2 3 1000 100 10 1

In the base 10 system, each digit of a number can have a value of 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9, giving a total of 10 possible values for each digit. Yep, that’s why it’s called base 10! But the actual value of each digit depends on its position within the number. Moving from right to left, each digit gets multiplied by an increasing power of 10. So the multiplier for the far-right position is 10 to the power of 0, which is 1. Moving to the left, the next multiplier is 10 to the power of 1, which is 10. Moving again to the left, the next multiplier is 10 to the power of 2, which is 100. And so on.

This means each digit has a value ten times that of the digit to its right. The number 423 is equal to the following:

(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.

Base 2 is often called binary, which you’ve likely heard of before. Base 2 has only two options for each digit: 0 or 1.

Almost all modern computers use binary because, at the physical level, it’s easiest to handle only two options for each digit. In digital electronic circuitry, which is mostly what comprises a computer, the presence of an electrical voltage is 1 and the absence is 0 — that’s base 2!

Note: There have been computers, both real and imagined, that use the ternary numeral system, which has three possible values instead of two. Computer scientists, engineers and dedicated hackers continue to explore the possibilities of a base-3 computer. See https://en.wikipedia.org/wiki/Ternary_computer and http://hackaday.com/tag/ternary-computer/.

Here’s a representation of the base 2 number 1101:

1 1 0 1 8 4 2 1

In the base 10 number system, the place values increase by a factor of 10: 1, 10, 100, 1000, etc. In base 2, they increase by a factor of 2: 1, 2, 4, 8, 16, etc. The general rule is to multiply each digit by an increasing power of the base number — in this case, powers of 2 — moving from right to left.

So the far-right digit represents (1 * 2^0), which is (1 * 1), which is 1. The next digit to the left represents (0 * 2^1), which is (0 * 2), which is 0. In the illustration above, you can see the powers of 2 on top of the blocks.

Put another way, every power of 2 either is (1) or isn’t (0) present as a component of a binary number. The decimal version of a binary number is the sum of all the powers of 2 that make up that number. So the binary number 1101 is equal to:

(1 * 8) + (1 * 4) + (0 * 2) + (1 * 1) = 13

And if you wanted to convert the base 10 number 423 into binary, you would simply need to break down 423 into its component powers of 2. You would wind up with the following:

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

As you can see by scanning the binary digits in the above equation, the resulting binary number is 110100111. You can prove to yourself that this equals 423 by doing the math!

The computer term given to each digit of a binary number is a bit (a contraction of “binary digit”). Eight bits make up a byte. Four bits is called a nibble, a play on words that shows even old-school computer scientists had a sense of humor.

A computer’s limited memory means it can generally deal with numbers up to a certain length. Each register, for example, is usually 32 or 64 bits in length, which is why we speak of 32-bit and 64-bit CPUs.

Therefore, a 32-bit CPU can handle a maximum base-number of 4,294,967,295, which is the base 2 number 11111111111111111111111111111111. That is 32 ones—count them!

A computer can handle numbers larger than the CPU maximum, but the calculations must be split up and managed in a special and longer way, much like the long multiplication you performed in school.

Hexadecimal Numbers

Working with binary numbers can become tedious because writing or typing them can take a long time. For this reason, in computer programming, we often use another number format known as hexadecimal or hex for short. This is base 16.

Of course, there aren’t 16 distinct numbers to use for digits; there are only 10. To supplement these, we use the first six letters, a through f.

They are equivalent to decimal numbers like so:

  • a = 10
  • b = 11
  • c = 12
  • d = 13
  • e = 14
  • f = 15

Here’s a base 16 example using the same format as before:

c 0 d e 4096 256 16 1

Notice first that you can make hexadecimal numbers look like words. That means you can have a little bit of fun. :]

Now the values of each digit refer to powers of 16. In the same way as before, you can convert this number to decimal like so:

(12 * 4096) + (0 * 256) + (13 * 16) + (14 * 1) = 49374

You translate the letters to their decimal equivalents and then perform the usual calculations.

But why bother with this?

Hexadecimal is useful because each hexadecimal digit can represent precisely four binary digits. The binary number 1111 is equivalent to hexadecimal f. You can simply concatenate the binary digits representing each hexadecimal digit, creating a hexadecimal number shorter than its binary or decimal equivalents.

For example, consider the number c0de from above:

c = 1100
0 = 0000
d = 1101
e = 1110

c0de = 1100 0000 1101 1110

This is helpful, given how computers use long 32-bit or 64-bit binary numbers. Recall that the largest 32-bit number in decimal is 4,294,967,295. In hexadecimal, it is ffffffff. That’s much more compact and clear.

How Code Works

Computers have many 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 correct order to produce something much bigger.

Coding is much like writing a recipe. You assemble ingredients (the data) and give the computer a step-by-step recipe for using them.

Here’s an example:

Step 1. Load photo from the 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.

This set of steps is what’s known as pseudo-code. It isn’t written in a valid computer programming language but represents the algorithm that you want to use. In this case, the algorithm takes a photo, resizes it, applies a filter and then prints it. It’s a relatively straightforward algorithm, but it’s an algorithm nonetheless!

Swift code is just like this: a step-by-step list of instructions for the computer. These instructions will get more complex as you read this book, but the principle is the same: You are simply telling the computer what to do, one step at a time.

Each programming language is a high-level, pre-defined way of expressing these steps. The compiler knows how to interpret the code you write and convert it into instructions the CPU can execute.

There are many different programming languages, each with its own advantages and disadvantages. Swift is a highly modern language. It incorporates the strengths of many other languages while ironing out some of their weaknesses. In years to come, programmers may look back on Swift as old and crusty, too. But for now, it continues to improve and evolve.

This chapter has briefly covered computer hardware, number representation and code, and how they all work together to create a modern program. That was a lot to cover in one section! Now it’s time to learn about the tools you’ll use to write in Swift as you follow along with this book.

Playgrounds

The set of tools you use to write software is called a 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.

Xcode includes a handy document type called a playground, which allows you to quickly write and test code without building a complete app. You’ll use playgrounds throughout the book to practice coding, so it’s essential to understand how they work. That’s what you’ll learn during the rest of this chapter.

Creating a Playground

To get started with a playground, click File ▸ New ▸ Playground. Xcode will present you with a choice of templates:

The platform you choose defines which version of the template Xcode will use to create the playground. Currently, your options are iOS or macOS. Each platform comes with its own environment set up and ready for you to begin playing around with code.

For this book, choose whichever platform you wish. You won’t be writing any platform-specific code; instead, you’ll be learning the core principles of the Swift language.

Select the Blank template and click Next. Xcode will now ask you to name the playground and select a location to save it.

The name is merely cosmetic and for your own use; when you create your playgrounds, feel free to choose names that will help you remember what they’re about. For example, while working through Chapter 1, “Expressions, Variables & Constants”, you may want to name your playground Chapter1.

Click Create to create and save the playground. Xcode then presents you with the playground, like so:

Even blank playgrounds don’t start empty but have some basic starter code to get you going. Don’t worry — you’ll soon learn what this code means.

Playgrounds Overview

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

The previous screenshot highlights the first and most important things to know about:

  1. Source editor: This is the area in which you’ll write your Swift code. It’s much like a text editor such as Notepad or TextEdit. You’ll notice the use of what’s known as a monospaced font, meaning all characters are the same width. This even spacing makes the code much easier to read and format.

  2. Results sidebar: This area shows the results of your code. You’ll learn more about how code executes as you read through the book. The results sidebar will be the main place to confirm your code is working as expected.

  3. Resources tree: This shows the list of resources contained within the playground. Here you’ll find a tree of resources for the playground, starting with the main playground file, then additional sources and resources. This allows you to build complex playgrounds that split the sources into multiple files.

  4. Execution control: This control lets you run the entire playground file or clear state so you can run it again. By default, playgrounds do not execute automatically. You can change this setting to execute with every change by long-pressing it and selecting “Automatically Run”.

  5. Activity viewer: This shows the status of the playground. The screenshot shows that the playground has finished executing and is ready to handle more code in the source editor. When the playground executes, this viewer will indicate this with a spinner.

  6. Left panel control: This toggles the left panel where the resources tree is. Keep this closed for now.

  7. Right panel control: This toggles the right panel. Here you’ll find information about the source file that’s open. You’ll usually keep this closed.

  8. Bottom panel control: This toggles the bottom panel. In here, you’ll find output from the running playground. You’ll open this later.

You can turn on line numbers on the left side of the source editor by clicking Xcode ▸ Preferences… ▸ Text Editing ▸ Line Numbers. Line numbers can be handy when you want to refer to parts of your code.

Playgrounds execute the code in the source editor from top to bottom. The play button floats next to each line as you move the cursor over it and lets you run from the beginning of the file up to and including the line you click. To force a re-execution, you can click on the Execution control button twice–once to stop and clear it and again to rerun.

Once the playground execution is finished, Xcode updates the results sidebar to show the results of the corresponding line in the source editor. You’ll see how to interpret the results of your code as you work through the examples in this book.

Note: Under certain conditions, Xcode may incorrectly disable line-based execution. In these cases, use the execution control button to run the entire playground.

Getting Started With Swift

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

You can follow along with your own playground. Simply create one and type in the code as you go!

First up is something that helps you organize your code. Read on!

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.

Like most other programming languages, Swift allows you to document your code using what are called comments. These allow you to write any text directly alongside your code and are ignored by the compiler.

The first way to write a comment is like so:

// This is a comment. It is not executed.

This is a single-line comment.

You could stack these up like so to allow you to write paragraphs:

// This is also a comment.
// Over multiple lines.

However, there is a better way to write comments which span multiple lines. Like so:

/* This is also a comment.
   Over many..
   many...
   many lines. */

This is a multi-line comment. The start is denoted by /* and the end is denoted by */. Simple!

Swift also allows you to nest comments like so:

/* This is a comment.

 /* And inside it
 is
 another comment.
 */

 Back to the first.
 */

This capability might not seem particularly interesting, but it may be if you have seen other programming languages. Many do not allow you to nest comments like this, as when it sees the first */; it thinks you are closing the first comment. Use code comments where necessary to document your code, explain your reasoning, or simply leave jokes for your colleagues. :]

Printing Out

It’s also useful to see the results of what your code is doing. In Swift, you can achieve this through the print command.

print will output whatever you want to the debug area (sometimes referred to as the console).

For example, consider the following code:

print("Hello, Swift Apprentice reader!")

This statement will output a nice message to the debug area like so:

You can hide or show the debug area using the button highlighted in the box in the above screenshot. You can also click View ▸ Debug Area ▸ Show Debug Area 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 between 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 Swift’s various arithmetic operations by considering how they apply to numbers. In later chapters, you 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 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 an expression, meaning each has a value. In these cases, all four expressions have the same value: 8. Notice how the code looks similar to how you would write the operations out on pen and paper. You can enter these straight into your playground.

The line numbers in light blue have not yet run. To run your code, click on the light-blue play button on the last line next to the cursor.

Upon running, the playground removes the blue sidebar from the lines that have run; you can also see the values of these expressions in the right-hand bar, known as the results sidebar.

If you want, you can remove the whitespace surrounding the operator:

2+6

When you make this change, the blue sidebar reappears to indicate which lines need to be rerun. You can run again by clicking the blue arrow or using the keyboard shortcut Shift-Enter.

Note: Shift-Enter runs all statements up to the current cursor and advances to the next line. This shortcut makes it easy to advance one line and run the entire playground step-by-step. It’s a great shortcut to commit to muscle memory.

Removing the whitespace is all or nothing; you can’t mix styles. For example:

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

The first error will be:

Consecutive statements on a line must be separated by ';'

And for the second error, you’ll see:

'+' is not a postfix unary operator

You don’t need to understand these error messages at the moment. Just be aware that you must have whitespace on both sides of the operator or no whitespace on either side!

It’s often easier to read expressions when you have white space on either side.

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

You may be surprised to know this results in the number 3. If you only use integers in your expression, Swift also 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 the statement 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. All of them are standard mathematical operations, just less common. Let’s turn to them now.

The first 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 line computes 28 divided by 10 and then truncates the result, chopping off any extra decimals and 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. Then they 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:

0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0

The digits that 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.

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 used this trick because shifting bits is much simpler for a CPU to do than complex multiplication and division arithmetic. Therefore the code was quicker if it used shifting.

However, CPUs are much faster these days, 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!

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)

Note 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 higher precedence than the addition operator (+), so the code executes the division operation first in this example.

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 at school. Multiply and divide have the same precedence, higher than add and subtract, which also have the same precedence.

Math Functions

Swift also has a vast range of math functions for you to use when necessary. You never know when you’ll need to pull out some trigonometry, especially when you’re a pro at Swift and writing games!

Note: Not all of these functions are part of Swift. The operating system provides some. Don’t remove the 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 convert an angle from degrees to radians and then compute the sine and cosine, respectively. Notice how both use Double.pi, a constant Swift provides us, ready-made with pi to as much precision as possible by the computer. Neat!

Then there’s this:

(2.0).squareRoot()
// 1.414213562373095

This code computes the square root of 2. Did you know that the sine of 45° equals 1 over the square root of 2? Try it out!

Not mentioning these would be a shame:

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((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 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.

In your Swift code, you can give each piece of data a name you can refer to later. The name carries with it a type annotation that denotes what sort of data the name refers to, such as text, numbers, or a date. You’ll learn about some basic types in this chapter and encounter many other types throughout this book.

Constants

Take a look at this:

let number: Int = 10

This code declares a constant called number, of type Int. Then it sets the value of the constant to the number 10.

Note: Thinking back to operators, here’s another one. The equals sign, =, the assignment operator.

The type Int can store integers. The way you store decimal numbers is like so:

let pi: Double = 3.14159

This constant is similar to the Int constant, except the name and the types are different. This time, the constant is a Double, which 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:

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 refer to the total number of seats installed, you could use a constant.

You might even use a constant for something like a person’s age. Even though their age will change as their birthday comes, 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, it would be rather dull! But as you’ve seen, changing the data behind a constant is impossible.

When you know you’ll need to change some data, 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.

Note: In Swift, you can optionally use underscores to make larger numbers more human-readable. The quantity and placement of the underscores is up to you.

Now 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 declared or reassigned a variable.

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. A good name specifically describes the role of a variable or constant. Here are some examples of good names:

  • personAge
  • numberOfPeople
  • gradePointAverage

Often a bad name is not descriptive enough. Here are some examples of bad names:

  • a
  • temp
  • average

The key is to ensure that you’ll understand what the variable or constant refers to when you reread it later. Don’t make the mistake of thinking you have an infallible memory! It’s common in computer programming to look back at your code as early as a day or two later and forget what it does. Make it easier by giving your variables and constants intuitive, precise names.

Also, note how the names above are written. In Swift, it is common to camel case names. For variables and constants, follow these rules to case your names properly:

  • Start with a lowercase letter.
  • If the name is made up of multiple words, join them together and start the other words with an uppercase letter.
  • If one of these words is an abbreviation, write the entire abbreviation in the same case (e.g.: sourceURL and urlDescription)

In Swift, you can even use the full range of Unicode characters. For example, you could declare a variable like so:

var 🐶💩: Int = -1

That might make you laugh, but use caution with special characters like these. They are harder to type and likely to bring you more pain than amusement.

Special characters like these probably make more sense in data that you store rather than in Swift code; you’ll learn more about Unicode in Chapter 9, “Strings.”

Increment and Decrement

A common operation that you will need is to increment or decrement a variable. In Swift, you achieve it like so:

var counter: Int = 0

counter += 1
// counter = 1

counter -= 1
// counter = 0

The counter variable begins as 0. The increment sets its value to 1, and then the decrement sets its value back to 0.

These operators are similar to the assignment operator (=), except they also perform an addition or subtraction. They take the current value of the variable, add or subtract the given value and assign the result to the variable.

In other words, the code above is shorthand for the following:

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

Similarly, the *= and /= operators do the equivalent for multiplication and division, respectively:

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!

  1. Declare a constant of type Int called myAge and set it to your age.
  2. Declare a variable of type Double called averageAge. Initially, set it to your own age. Then, set it to the average of your age and the age of 30.
  3. Create a constant called testNumber and initialize it with whatever integer you want. Next, create another constant called evenOdd and set it equal to testNumber modulo 2. Now change testNumber to various numbers. What do you notice about evenOdd?
  4. Create a variable called answer and initialize it with the value 0. Increment it by 1. Add 10 to it. Multiply it by 10. Then, shift it to the right by 3. After all of these operations, what’s the answer?

Challenges

Before moving on, here are some challenges to test your knowledge of variables and constants. It is best to 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)

Modify the first line so that it compiles. Did you use var or let?

Challenge 3: Compute the Answer

Consider the following code:

let x: Int = 46
let y: Int = 10

Work out what answer equals when you add the following lines of code:

// 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 is 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 then be 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 using the function arc4random(). This function picks 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. (Hint: You must include the line import Foundation to access arc4random(). If this method of creating a random number seems primitive, you are right! There is an easier, more expressive way to generate random numbers you will learn about in Chapter 4, “Advanced Control Flow”.)

Challenge 9: Quadratic Equations

A quadratic equation has the form a⋅x² + b⋅x + c = 0. The values of x which satisfy this are 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

  • Computers, at their most fundamental level, perform simple mathematics.

  • A programming language allows you to write code, which the compiler converts into instructions that the CPU can execute.

  • Computers operate on numbers in base 2 form, otherwise known as binary.

  • The IDE you use to write Swift code is named Xcode.

  • By providing immediate feedback about how code is executing, playgrounds allow you to write and test Swift code quickly and efficiently.

  • Code comments are denoted by a line starting with // or multiple lines bookended with /* and */.

  • You use comments to document your code.

  • You can use print to output information to the debug area.

  • The arithmetic operators are:

    Add: +
    Subtract: -
    Multiply: *
    Divide: /
    Remainder: %
    
  • Swift makes many functions min(), max(), squareRoot(), sin() and cos(). You will learn many more throughout this book.

  • Constants and variables give names to data.

  • Once you’ve declared a constant, you can’t change its data, but you can change a variable’s data at any time.

  • Always give variables and constants meaningful names to save yourself and your colleagues headaches later.

  • Operators to perform arithmetic and then assign back to the variable:

    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.
© 2024 Kodeco Inc.