Swift Programming from Scratch

The Swift Sandbox is integrated, making the exercises interactive. Read more about the book here.

Chapter 1: First Steps

What is a computer program?

A program is a list of instructions that are followed one after the other by a computer. You are most likely familliar with lists of instructions in everyday life. An example of a list of instructions would be a cooking recipe:

Fried eggs:

heat 2 tablespoons of butter in a non-stick frying pan. break the eggs and slip into pan one at a time. cook until whites are completely set and yolks begin to thicken. carefully flip eggs. cook second side to desired doneness. sprinkle with salt and pepper. serve immediately.

Another example is this list of instructions on how to put on a life jacket:

The lists of instructions mentioned above are made to be executed by people. Computer programs are simillarly just lists of instructions but they are meant to be executed by computers. They are meant to be readable and understandable by humans but executing them would often be highly impracticable.

For example the program used for drawing a single screen in a modern game executes hundred of millions of mathematical operations like additions and multiplications. Executing such a list of instructions would take any person an embarasing amount of time, yet computers can happily do it 60 times per second.

Why do we need a programming language?

Lists of instructions like cooking recipes and putting on a life jacket are quite easy to understand for humans but they’re incrediblly difficult to understand for a computer. Programming languages are designed as a way of giving a computer instructions that it can easily understand. That is because a programming language (like Swift) is much less ambigous than a language like english. Also it closely resembles the way in which a computer works.

In this book you’ll learn the basics of programming using Swift. More importantly this will teach you about the kind of instructions that your computer understands and building programs for it to execute.

Whether you want to build an app, a game or a website the basic principles remain the same. You have to write a program for the computer to execute and writing such a program is done using a programming language.

Why Swift?

The Swift programming language was introduced in June 2014 by Apple, since then it has grown immensly in popularity. Swift is primarly used for developing apps and games for the iPhone and the Mac and provides an easier and more enjoyable way of doing that.

We’ll start looking at basic concepts one by one now. We encourage you to experiment with the code we introduce by typing the statements into the code boxes and changing values around.

Variables and Constants

Use the var keyword to declare a variable and the let keyword to declare a constant. Variables and constants are named values. Variable can change their value over time and constants don’t. To change the value of a variable you need to asign it a new one.

// declares a variable named a that has the value 1 var a = 1 // assigns the value 2 to the variable a a = 2 // a has the value 2 // declares a constant named one with the value 1 let one = 1 one = 2 // this gives an error because we cannot change the value of a constant

the text after // is called a comment. Comments are ignored by the computer when executing the program. They are usually used to explain parts of code

Naming Variables

Variables should usually be named using alphabetical characters. For example: sum , number , grade , money

If you want your variable’s name to contain multiple words then you should start each word in the name with an uppercase letter except for the first one. For example you want a variable that holds the number of students in a class than you should name it numberOfStudents instead of numberofstudents because the first one is more readable.

This naming convention is called CamelCase.

It’s recommanded to use descriptive names for variables. But don’t overdo it, for example numberOfStudents is a reasonable name while numberOfStudentsInTheCurrentClass is too long. A good rule of thumb is to use at most 3 words for the name of a variable.

We could have used a way shorter name for the variable above, for example we could have called it n . The disadvantage with short variable names is that they’re not expressive. If you read your code after 2 months you most likely won’t remember what n means. But numberOfStudents is immediately obvious.

Generally its not a good idea to have variables that consist of a single letters but there are some exceptions.

When dealing with numbers that don’t represent something it’s ok to use single letter names.

Basic Operators

You can write arithmetic expressions using numbers, variables, operators and parentheses.

// The + operator returns the sum of two numbers let sum = 1 + 2 // 3 // The - operator returns the difference of two numbers let diff = 5 - sum // 5 - 3 = 2 // The * operator returns the product of two numbers let mul = sum * diff // 3 * 2 = 6 // The / operator returns the numbers of times the divisor(the number on // the right side) divides into the dividend(the number on the left side) // For example, when dividing 6 by 3, the quotient is 2, while 6 is called // the dividend, and 3 the divisor. // 13 divided by 5 would be 2 while the remainder would be 3. let div = mul / diff // 6 / 2 = 3 // The remainder(modulo) operator returns the remainder of the division let mod = 7 % 3 // 1 because 7/3 = 2 and remainder 1 (2 * 3 + 1 = 7) // You can use parentheses to group operations ( 1 + 1 ) * ( 5 - 2 ) // Multiplication, division and remainder have higher precedence than // addition and subtraction. // For example: 5 + 2 * 3 = 5 + 6 = 11

Integer Division

Addition, subtraction and multiplication behave pretty much as you expect. The tricky operations are division and remainder.

Take for example 5 / 2 . Normally you’d expect the result to be 2.5 . In Swift dividing two integers also produces an integer this is acomplished by discarding the part of the number after the decimal point. So 5 / 2 = 2 .

The remainder operator or modulo operator (%) is used to get the remainder of an integer division. 5 % 2 = 1

For 5 / 2 :

quotient = 5 / 2 = 2

remainder = 5 % 2 = 1

quotient * 2 + remainder = 5

Generally speaking for two integers a and b this equations always hold

quotient = a / b

remainder = a % b

b * quotient + remainder = a

NOTICE: remainder = a - b * quotient

This implies that remainder = a - b * (a / b) and

a % b = a - b * (a / b)

You can view a % b as a shorthand way of computing a - b * (a / b)

NOTICE: if a % b = 0 then b divides a , that is a is a multiple of b .

Example:

15 / 5 = 3

15 % 5 = 0 ->

15 = 5 * 3

Order of statemets

The order of statements in a program matters. Like lists of instructions programs are executed from top to bottom.

var numberOfApples = 7 // you have 7 apples var numberOfOranges = 2 // you have 2 orages // you eat an apple (numberOfApples = 6) numberOfApples = numberOfApples - 1 // a wizard doubles your oranges (numberOfOranges = 4) numberOfOranges = numberOfOranges * 2 var stashedFruits = numberOfApples + numberOfOranges // 10 (6 + 4) // you receive 2 apples (numberOfApples = 8). stashedFruits remains unchanged! numberOfApples += 2 stashedFruits /= 2 // you lose half your stashed fruits 5 (10 / 2)

In the program above the variable stashedFruits gets a value only after all the previous statements are run. Also notice that the value assigned to a variable is computed at the time of assignment. Changing numberOfApples after declaring stashedFruits will not have any effect on the value of stashedFruits .

Print Statement

After making some computations you will want to show your results somehow. The simplest way to do it is with print() statement.

// will print Hello Swift! in the console // you can print any text between quotes print ( " Hello Swift! " ) print ( 1 + 2 ) // will print 3 var ten = 10 print (ten) // will print 10

1.1 Sum

You are given two variables a and b , compute their sum and store it in another variable named sum then print the result.

Example 1 Input: var a = 1 var b = 2 Expected values: sum = 3 Output: 3 [collapse]

Example 2 Input: var a = 13 var b = 22 Expected values: sum = 35 Output: 35 [collapse]

Solution var a = 1 var b = 2 var sum = a + b print (sum) [collapse]

1.2 Seconds

Determine the number of seconds in a year and store the number in a variable named secondsInAYear .



Hint The number of seconds in a year is 365 times the number of seconds in a day.

The number of seconds in a day is 24 times the number of seconds in a hour.

The number of seconds in a hour is 60 times the number of seconds in a minute, which is 60. [collapse]

Solution let secondsInAMinute = 60 // The number of seconds in a hour is 60 times the number // of seconds in a minute, which is 60. let secondsInAHour = 60 * secondsInAMinute // The number of seconds in a day is 24x the number of seconds in a hour. let secondsInADay = 24 * secondsInAHour // The number of seconds in a year is 365x the number of seconds in a day. let secondsInAYear = 365 * secondsInADay [collapse]

1.3 Pixels

Your are given the width and height of a screen in pixels. Calculate the total number of pixels on the screen and store the result in a variable named numberOfPixels .

Example 1 Input: var width = 4 var height = 3 Expected values: numberOfPixels = 12 [collapse]

Example 2 Input: var width = 1920 var height = 1080 Expected values: numberOfPixels = 2073600 [collapse]

Hint Consider a 5×3 screen like this: ***** ***** ***** The number of pixels on this screen is 5 + 5 + 5 = 5 * 3 [collapse]

Solution var width = 1920 var height = 1080 var numberOfPixels = width * height [collapse]

1.4 Sum and Difference

You are given the sum and the difference of two numbers. Find out the values of the original numbers and store them in variables a and b .

Example 1 Input: var sum = 16 var dif = 4 Expected values: a = 10 b = 6 [collapse]

Example 2 Input: var sum = 2 var dif = 0 Expected values: a = 1 b = 1 [collapse]

Example 3 Input: var sum = 4 var dif = 2 Expected values: a = 3 b = 1 [collapse]

Hint 1 sum + diff = a + a + b - b

sum + diff = 2 * a [collapse]

Hint 2 sum = a + b

b = sum - a [collapse]

Solution let sum = 16 // a + b let diff = 4 // a - b // sum + diff = a + b + a - b = a + a = 2*a // -> sum + diff = 2*a // -> a = (sum + diff) / 2 var a = (sum + diff) / 2 // 10 var b = sum - a // 6 [collapse]

1.5 L Area

You are given four variables width , height , x , y that describe the dimensions of a L-shape as shown in the image below. Determine the perimeter and area of the described L-shape. Store the value of the perimeter in a variable named perimeter , and the area in a variable named area .

Example 1 Input: var width = 8 var height = 12 var x = 4 var y = 3 Expected values: perimeter = 40 area = 60 [collapse]

Example 2 Input: var width = 8 var height = 4 var x = 2 var y = 2 Expected values: perimeter = 24 area = 20 [collapse]

Hint The perimeter of the L-shape is the same as of a rectangle of size width X height . To compute the area you can imagine the L-shape as rectangle of size width X height with a rectangle of size (width-x) X (height-y) cut out. [collapse]

Solution var width = 8 var height = 12 var x = 4 var y = 3 var perimeter = 2 * (width + height) var bigArea = width * height var smallArea = (width - x) * (height - y) var area = bigArea - smallArea [collapse]

1.6 Swap

Given two variable a and b , swap their values. That is the new value of a will become the old value of b and vice versa.

Example 1 Input: var a = 1 var b = 2 Expected values: a = 2 b = 1 [collapse]

Example 2 Input: var a = 13 var b = 7582 Expected values: a = 7582 b = 13 [collapse]

Hint 1 Just assigning a to the value of b and b to the value of a will not work. var a = 1 var b = 2 a = b // a will have the value 2. The original value of a is lost b = a // b will remain the same [collapse]

Hint 2 Use a third variable to save the original value of a . [collapse]

Solution var a = 1 var b = 2 var temp = a a = b b = temp [collapse]

1.7 Last digit

You are given a number a . Print the last digit of a .

Example 1 Input: var a = 123 Output: 3 [collapse]

Example 2 Input: var a = 337 Output: 7 [collapse]

Example 3 Input: var a = 100 Output: 0 [collapse]

Hint Use the remainder % operator.

Remember that a = k * (a / k) + a % k

Can you think of a value for k that gives the last digit? [collapse]

Solution var a = 123 print (a % 10 ) [collapse]

1.8 Dog Years

You are given Rocky’s age in dog years. Print Rocky’s age in human years. You know that 1 human year is 7 dog years.

Example 1 Input: var rockysAge = 50 Output: 7 [collapse]

Example 2 Input: var rockysAge = 14 Output: 2 [collapse]

Example 3 Input: var rockysAge = 15 Output: 2 [collapse]

Hint Use division. [collapse]

Solution var rockysAge = 50 var rockysAgeInHumanYears = rockysAge / 7 print (rockysAgeInHumanYears) // 7 [collapse]

1.9 Brothers

Everyone hates solving word problems by hand so let’s make a program to solve them for us.

x years from now Alice will be y times older than her brother Bob. Bob is 12 years old. How many years does Alice have?

Example 1 Input: var x = 3 var y = 2 var bob = 12 Expected values: alice = 27 [collapse]

Example 2 Input: var x = 1 var y = 3 var bob = 12 Expected values: alice = 38 [collapse]

Hint alice + x = y * (bob + x)

Solve for alice [collapse]

Solution var x = 3 var y = 2 var bob = 12 // alice + x = (bob + x) * y // alice = (bob + x) * y - x var alice = (bob + x) * y - x [collapse]

1.10 Apples and Oranges

You have x apples. Bob trades 3 oranges for 5 apples. He does not accept trades with cut fruit.

How many oranges can you get from Bob and how many apples will you have left?

The number of apples you will have left should be stored in a variable named apples . The number of oranges you will have after the trade should be stored in a variable named oranges .

Example 1 Input: var x = 17 Expected values: apples = 2 oranges = 9 [collapse]

Example 2 Input: var x = 25 Expected values: apples = 0 oranges = 15 [collapse]

Example 3 Input: var x = 4 Expected values: apples = 4 oranges = 0 [collapse]

Hint Use the division( / ) and the remainder( % ) operator [collapse]

Solution var x = 17 var apples = x % 5 var oranges = x / 5 * 3 [collapse]

1.11 Boys and Girls

A class consists of numberOfBoys boys and numberOfGirls girls.

Print the percentage of boys in the class followed by the percentage of girls in the class. The percentage should be printed rounded down to the nearest integer. For example 33.333333333333 will be printed as 33 .

Example 1 Input: var numberOfBoys = 20 var numberOfGirls = 60 Output: 25 // percentage of boys 75 // percentage of girls [collapse]

Example 2 Input: var numberOfBoys = 20 var numberOfGirls = 20 Output: 50 // percentage of boys 50 // percentage of girls [collapse]

Example 3 Input: var numberOfBoys = 10 var numberOfGirls = 20 Output: 33 // percentage of boys 66 // percentage of girls [collapse]

Hint First you’ll have to compute the total number of students in the class [collapse]

Hint 1 numberOfStudents … 100%

numberOfBoys … X% [collapse]

Hint 2 numberOfStudents / 100 = numberOfBoys / X [collapse]

Solution var numberOfBoys = 20 var numberOfGirls = 60 var numberOfStudents = numberOfBoys + numberOfGirls var boyPercentage = numberOfBoys * 100 / numberOfStudents print (boyPercentage) var girlPercentage = numberOfGirls * 100 / numberOfStudents print (girlPercentage) [collapse]

Swift Programming from Scratch

Read more about the book here.