Swift Programming from Scratch
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:
- 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.
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.
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.
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.
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
Variables should usually be named using alphabetical characters. For example:
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.
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
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
5 / 2:
quotient = 5 / 2 = 2
remainder = 5 % 2 = 1
quotient * 2 + remainder = 5
Generally speaking for two integers
b this equations always hold
quotient = a / b
remainder = a % b
b * quotient + remainder = a
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)
a % b = 0 then
a, that is
a is a multiple of
15 / 5 = 3
15 % 5 = 0 ->
15 = 5 * 3
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
After making some computations you will want to show your results somehow. The simplest way to do it is with
// 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
You are given two variables
b, compute their sum and store it in another variable named
sum then print the result.
var a = 1 var b = 2
sum = 3
var a = 13 var b = 22
sum = 35
var a = 1 var b = 2 var sum = a + b print(sum)
Determine the number of seconds in a year and store the number in a variable named
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
Your are given the
height of a screen in pixels. Calculate the total number of pixels on the screen and store the result in a variable named
var width = 4 var height = 3
numberOfPixels = 12
var width = 1920 var height = 1080
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
You are given the
sum and the
difference of two numbers. Find out the values of the original numbers and store them in variables
var sum = 16 var dif = 4
a = 10 b = 6
var sum = 2 var dif = 0
a = 1 b = 1
var sum = 4 var dif = 2
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
You are given four variables
y that describe the dimensions of a L-shape as shown in the image below. Determine the
area of the described L-shape. Store the value of the perimeter in a variable named
perimeter, and the area in a variable named
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
Given two variable
b, swap their values. That is the new value of
a will become the old value of
b and vice versa.
var a = 1 var b = 2
a = 2 b = 1
var a = 13 var b = 7582
a = 7582 b = 13
a to the value of
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
var a = 1 var b = 2 var temp = a a = b b = temp
You are given a number
a. Print the last digit of
var a = 123
var a = 337
var a = 100
Use the remainder
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)
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.
var rockysAge = 50
var rockysAge = 14
var rockysAge = 15
var rockysAge = 50 var rockysAgeInHumanYears = rockysAge / 7 print(rockysAgeInHumanYears) // 7
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?
var x = 3 var y = 2 var bob = 12
alice = 27
var x = 1 var y = 3 var bob = 12
alice = 38
alice + x = y * (bob + x)
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
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
var x = 17
apples = 2 oranges = 9
var x = 25
apples = 0 oranges = 15
var x = 4
apples = 4 oranges = 0
Use the division(
/) and the remainder(
var x = 17 var apples = x % 5 var oranges = x / 5 * 3
A class consists of
numberOfBoys boys and
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
var numberOfBoys = 20 var numberOfGirls = 60
25 // percentage of boys 75 // percentage of girls
var numberOfBoys = 20 var numberOfGirls = 20
50 // percentage of boys 50 // percentage of girls
var numberOfBoys = 10 var numberOfGirls = 20
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
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.
?You can buy Training app + the PDF and ePub versions of the book!