**Swift Programming from Scratch **

The book is **updated for Swift 3** and the Swift Sandbox is integrated, making the exercises interactive. Read more about the book here.

- First Steps
- Conditionals
- Types
- Loops
- Strings
- Arrays
- Functions
- Recursion
- Closures
- Tuples & Enums
- Dictionaries

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

The great news is that Swift is also a great programming language for learning to code because of the **Playgrounds**feature described below.

**Using Playgrounds**

Playgrounds provide a fun and interactive way of writing code. Traditionally you would write a program and run it to see its results. With playgrounds you can see the results of your program imedially as you type it. This gives you a lot of opportunity for experimenting and makes learning faster.

If you have the companion app for this book than clicking on an exercise will open a playground for you to start coding.

If you don’t have the companion app installed than you can use our integrated Swift Sandbox. All exercises are interactive and you can get automated feedback right on this page.

Another option would be to open Xcode and create a new playground by clicking the “Get started with a playground” button. Select OS X As your Platform and choose a destination where you want to save the Playground.

**Note:** If you don’t have Xcode installed, you can download the latest version from here

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 a playground 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 and more Playgrounds**

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`

.

Looking at the code above in a playground will give you an idea of why playgrounds are incredibly helpful for visualizing how code behaves.

As you can see each line of code in a playground has the value of the expression on that line printed in the right area of the screen.

Now, the cool thing is that if we modify any values. All lines are imediatelly updated to reflect our changes. For example we modify:

```
var numberOfApples = 25
var numberOfOranges = 30
```

and everything is recalculated and displayed immediately.

Try playing around!

**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
```

To see the console output in Playground make sure to show the `Debug Area`

.

You can do that by pressing the middle button from the top right corner of the Playground.

Or from the menu:

This is how the code from the example would look with the `Debug Area`

visible:

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

Input:

```
var a = 1
var b = 2
```

Expected values:

`sum = 3`

Output:

```
3
```

Input:

```
var a = 13
var b = 22
```

Expected values:

`sum = 35`

Output:

```
35
```

```
var a = 1
var b = 2
var sum = a + b
print(sum)
```

**1.2 Seconds**

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

.

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.

```
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
```

**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`

.

Input:

```
var width = 4
var height = 3
```

Expected values:

`numberOfPixels = 12`

Input:

```
var width = 1920
var height = 1080
```

Expected values:

`numberOfPixels = 2073600`

Consider a 5×3 screen like this:

```
*****
*****
*****
```

The number of pixels on this screen is 5 + 5 + 5 = 5 * 3

```
var width = 1920
var height = 1080
var numberOfPixels = width * height
```

**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`

.

Input:

```
var sum = 16
var dif = 4
```

Expected values:

```
a = 10
b = 6
```

Input:

```
var sum = 2
var dif = 0
```

Expected values:

```
a = 1
b = 1
```

Input:

```
var sum = 4
var dif = 2
```

Expected values:

```
a = 3
b = 1
```

`sum + diff = a + a + b - b`

`sum + diff = 2 * a`

`sum = a + b`

`b = sum - a`

```
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
```

**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`

.

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.

```
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
```

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

Input:

```
var a = 1
var b = 2
```

Expected values:

```
a = 2
b = 1
```

Input:

```
var a = 13
var b = 7582
```

Expected values:

```
a = 7582
b = 13
```

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
```

Use a third variable to save the original value of `a`

.

```
var a = 1
var b = 2
var temp = a
a = b
b = temp
```

**1.7 Last digit**

You are given a number `a`

. Print the last digit of `a`

.

Input:

`var a = 123`

Output:

```
3
```

Input:

`var a = 337`

Output:

```
7
```

Input:

`var a = 100`

Output:

```
0
```

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?

```
var a = 123
print(a % 10)
```

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

Input:

`var rockysAge = 50`

Output:

```
7
```

Input:

`var rockysAge = 14`

Output:

```
2
```

Input:

`var rockysAge = 15`

Output:

```
2
```

Use division.

```
var rockysAge = 50
var rockysAgeInHumanYears = rockysAge / 7
print(rockysAgeInHumanYears) // 7
```

**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?

Input:

```
var x = 3
var y = 2
var bob = 12
```

Expected values:

`alice = 27`

Input:

```
var x = 1
var y = 3
var bob = 12
```

Expected values:

`alice = 38`

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

Solve for `alice`

```
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
```

**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`

.

Input:

`var x = 17`

Expected values:

```
apples = 2
oranges = 9
```

Input:

`var x = 25`

Expected values:

```
apples = 0
oranges = 15
```

Input:

`var x = 4`

Expected values:

```
apples = 4
oranges = 0
```

Use the division(`/`

) and the remainder(`%`

) operator

```
var x = 17
var apples = x % 5
var oranges = x / 5 * 3
```

**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`

.

Input:

```
var numberOfBoys = 20
var numberOfGirls = 60
```

Output:

```
25 // percentage of boys
75 // percentage of girls
```

Input:

```
var numberOfBoys = 20
var numberOfGirls = 20
```

Output:

```
50 // percentage of boys
50 // percentage of girls
```

Input:

```
var numberOfBoys = 10
var numberOfGirls = 20
```

Output:

```
33 // percentage of boys
66 // percentage of girls
```

First you’ll have to compute the total number of students in the class

`numberOfStudents`

… `100%`

`numberOfBoys`

… `X%`

`numberOfStudents / 100`

= `numberOfBoys / X`

```
var numberOfBoys = 20
var numberOfGirls = 60
var numberOfStudents = numberOfBoys + numberOfGirls
var boyPercentage = numberOfBoys * 100 / numberOfStudents
print(boyPercentage)
var girlPercentage = numberOfGirls * 100 / numberOfStudents
print(girlPercentage)
```

Feel free to ask any questions in the comments bellow.

**Swift Programming from Scratch**

Read more about the book here.

- First Steps
- Conditionals
- Types
- Loops
- Strings
- Arrays
- Functions
- Recursion
- Closures
- Tuples & Enums
- Dictionaries

?You can buy **Training app** + the **PDF** and **ePub** versions of the book!

Hello merry xmas, and happy new year.

Can you explain me the 1.9 and 1.10 please

Hello Eduardo,

A Happy new year to you too

1.9

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

code:

var x = 3

var y = 2

var bob = 12 // bob has 12 years

Alice has alice years. in x years she will have alice+x and bob will have 12+x. Then alice will have y times as much as her brother.

alice + x // alice’s age in x years

bob + x // bob’s age in x years

alice + x = (bob + x) * y // alice will have y times as much as her brother

alice = (bob + x) * y – x // by subtracting x we get alice’s current age – we also know the value of each variable on the right side of the equation

1.10

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?

If Bob only accepts trades with cut fruit that mean that you have to give him 5 apples for 3 oranges each time.

To get the maximum amount of oranges you have to trade as many times 5 apples for 3 oranges.

You are asked how many times you can trade 5 apples from the x you have and how many you are left with after all the trades.

If x is divisible with 5 the you can trade all your oranges. for example 10 apples will be traded for 6 oranges. If x is not divisible with 5 the you are going to get stuck with the remainder of the division of x by 5.

To find you how many trades you can make you will need to divide x by 5. The number of trades times 3 oranges is the number of oranges you will get from the trades.

Hi, these are very helpful especially combined with the current demo app.

But problem 1.11 is not on the app currently, however, though all of 2.x seems to be live.

Thanks, can’t wait to use the full version.

1.9 is worded oddly. “How many years does Alice have?”

Took me way to long to figure out what you were asking me to do.

Thank you for you feedback – we are going to revise the problem description for 1.9 in the next version of the book

Hi.

In 1.11 Boys and Girls:

I tried using

var boyPercentage = numberOfBoys / numberOfStudents * 100

And recieved 0 as Output. How come that be?

Shouldn’t NumberOfBoys(80) / NumberOfStudents = 0,25

0,25 * 100 = 25?

division and multiplication have the same priority. It’s actually 0 * 100 because partial results are still integers.

you should try 100 * numberOdBoys / numberOfStudents

The solution for 1.11 does not round to the nearest whole digit as being asked.

Solution:

var numberOfBoys: Double = 21

var numberOfGirls: Double = 60

var fullClass = numberOfBoys + numberOfGirls

var percentOfBoys = numberOfBoys / fullClass * 100

var percentOfGirls = numberOfGirls / fullClass * 100

var percentBoys = Int(percentOfBoys)

var percentGirls = Int(percentOfGirls)

if you work with integers that happens implicitly – also in the first chapter there is no mention of the Double type.

Your using ‘var’ everywhere when you should be using ‘let’. Only use ‘var’ if you really need a value to vary and none of the examples above need that. Teach good practice from day one not as a complication that is added later.

1.5 L Area Example 1.

Looks like area value should be 56, not 60 please check.

Area is still 60. I even counted the grey squares to make extra sure

1.7 Last digit

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

var a = 123

— a = 123

— The last digit of ‘a’ is 3

— a % 4 = 3

— how is print(a % 4) the wrong answer?

in that case all is ok. but is a % 4 a good solution if a where 5?

The exercise platform replaces the value of

`a`

with a list of values in order to evaluate your code.