You are on page 1of 49

Contents

1. Getting Started
a. What is Swift? 4
b. What is a programming language? 4
c. Pre-requisite 5
d. Installation of Development Platform 6
e. Opening the IDE 7
f. My first Swift program 8

2. Chapter 1: Variables
a. What are variables? 11
b. What are constants? 12
c. Get the value of a variable 13
d. Comments 13
e. Updating the value of a variable 14
f. Why do we use variables? 14
g. Mathematical operators 15
h. Strings 16
i. String concatenation 17
j. Data types 18
k. Type casting 18
l. Exercise 19

2
© Copyright Codomo Pte Ltd 2018
Contents

3. Chapter 2: For-Loop
a. What is a for loop? 22
b. Breakdown (for loop) 23
c. Nested for loop 24
d. Breakdown (nested for loop) 25
e. Exercise 26

4. Chapter 3: While Loop


a. What is a while loop? 29
b. Breakdown (while loop) 30
c. Comparison operators 31
d. Logical operators 31
e. Comparisons & logical operators in Swift 32
f. Exercise 33

5. Chapter 4: If-Else & Switch statement


a. What is an if-else statement? 37
b. Breakdown (if statement) 38
c. What is a switch statement? 39
d. Breakdown (switch statement) 40
e. Exercise 41

6. Swift Syntax Cheat Sheet 44

7. Answer Sheet 45
3
© Copyright Codomo Pte Ltd 2018
Getting Started
What is Swift?
Developed by Apple, Swift is a powerful and
intuitive programming language for apple devices
that run macOS, iOS, watchOS and tvOS.

iOS Development MacOS Development watchOS / TV


Development

Err.. what’s a programming language?


Just like humans communicate with one another using many
different languages, computers use programming languages to
communicate with other computers.

Human language Computer language

4
© Copyright Codomo Pte Ltd 2018
Getting Started
Pre-requisite

OR
Macbook iPad
Version: macOS 10.13.2 or later Version: iOS 10.3 or later

How to check the version of my Macbook?

1. Click on the apple icon on the top-left part of the screen


2. Go to “About This Mac”
3. Check version number

How to check the version of my iPad?

1. Go to “Settings” > “General” > “Software Update”


2. You will see the version number.

5
© Copyright Codomo Pte Ltd 2018
Getting Started
Installation of Development Platform

XCode and Swift Playgrounds are the Integrated Development


Environment (IDE) for Macbook and the iPad respectively. IDE, in
simple terms, is a software application where you build and run
codes.

Installing XCode

+ 1. Go to App Store
2. Search “XCode”
Macbook XCode 3. Download it.

OR
Installing Swift Playgrounds
+ 1. Go to App Store
Swift 2. Search “Swift Playgrounds”
iPad 3. Get it.
Playgrounds

6
© Copyright Codomo Pte Ltd 2018
Getting Started
Opening the IDE

XCode

1. Choose “Get started with a


playground”
2. Pick any name and choose
iOS as the platform
3. Click “Next”
4. Save this playground project

OR
Swift Playground

1. Choose “Get started with a


playground”
2. Pick any name and choose
iOS as the platform
3. Click “Next”
4. Save this playground project

7
© Copyright Codomo Pte Ltd 2018
Getting Started
My first Swift Program
We’re going to write our very first Swift program that will display
“Ahoy Matey” when run. Ready? Let’s go!

Note: For the subsequent parts of the tutorial, we will be using the
XCode as the main IDE. Do note that the code will work exactly
the same way in the iPad.

MyPlayground Project

8
© Copyright Codomo Pte Ltd 2018
Getting Started
Let’s write our first code.
1. Delete all the code statements. Let’s not go into the advanced
concept of import yet, shall we? :)
2. Type “print (‘Ahoy Matey’)” (without “”)
3. Wait for a few seconds. You will see “Ahoy Matey” at the
bottom of the IDE.

2
1. Source Editor: This is the area where you write your Swift code.
2. Debug Area: This is where the result of your Swift code will be displayed.

What’s happening?
When you write “print (‘Ahoy Matey’)”, you are simply telling the
system to print out the line “Ahoy, Matey!”.

ACTIVITY: SAY HELLO TO YOURSELF


Try printing “Hello <your first name>” and see what happens.

9
© Copyright Codomo Pte Ltd 2018
Variables
What are variables?
A variable acts like a container that stores data. For example, we
can use a variable to represent the number of crew members in a
ship. Below is a ship with 10 potatoes. Create a variable called
“crew” by typing “var crew:Int = 10”. “crew” is the variable name,
and 10 is the value that it stores. More examples ahead.

In Potato Pirates In Swift

var crew:Int = 10

Data type of variable

var crew:Int = 10

Initialising a variable Name of variable Value of variable

11
© Copyright Codomo Pte Ltd 2018
Variables
What are constants?
Similar to a variable, a constant carries a value of a particular type
(like the number 15 or the string “Ahoy”). You can then use it to
refer to that value many times in your program. However, the
value of a constant is immutable, which means that it cannot be
changed. You declare constant using “let” instead of “var”.

In Potato Pirates In Swift

let crew:Int = 10

Initialising a
constant let crew:Int = 10

Okay… then why don’t we declare everything as variables?

While variable accepts changes, there are special optimisation that


the compiler can make for constant values. When you use
constants for values that won't change, the compiler can make
low-level assumptions about how to store the value. In short, using
constants allow your program to execute faster.

12
© Copyright Codomo Pte Ltd 2018
Variables
Getting the value of a variable
After storing a value in a variable we can retrieve it by “calling” its
name. The code below demonstrates how to retrieve a value stored
in a variable.

Swift Code:
var crew:Int = 10 // create a variable called crew
print (crew) // print the value of crew

Console:

Psst.. // is a symbol for


comments in Swift.

Comments ( // symbol )
A comment is a programmer-readable explanation which is usually
used to explain the meaning of certain lines of code. Words
appearing after // will be ignored by the computer. Very useful!

13
© Copyright Codomo Pte Ltd 2018
Variables
Updating the value of a variable
You get a Potato King card, and receive 2 extra potatoes. How do
we increase the value of crew by 2? See below.

var crew:Int = 10 // create a variable called crew


crew = crew + 2 // Increase crew by 2
print (crew) // print the value of crew

ACTIVITY: I DARE YOU TO UPDATE A CONSTANT


Try increasing the value of a constant by 2 and see what happens.
The clue is in page 8.

Why do we use variables?


Data is constantly changing. To handle all these changes, values
need to be stored in a variable, which can then be modified.

10 crew 6 crew 3 crew

You may start with 10... ..and end up with 3!

14
© Copyright Codomo Pte Ltd 2018
Variables
Mathematical Operators
When writing code, the BODMAS order of operations still applies.
If you’ve forgotten your BODMAS rules this could help jog your
memory:

Brackets: ( ) Division: / Addition: +

BODMAS
Order Multiplication: * Subtraction: -

Note: There is also the modulo (or remainder) operator: %. It


returns the remainder when the number to its left is divided by the
number to its right. E.g.
10%2 = 0
5%2 = 1
20%3 = 2

Can you guess the answer? 4) 7


3) 3
1) (2+2)-1 2) 21
2) (14*9)/6 1) 3
3) 17%(3+4) Answer
4) 49/(17%10)

Try your best to answer these


questions without coding them!

15
© Copyright Codomo Pte Ltd 2018
Variables
Strings
The word ‘string’ is really just a fancy word for a bunch of
characters put together. To let the computer know that you’re
using a string, put your characters into quotation marks ("").

Oh, and don’t forget to use ‘String’ as your data type when
initialising it! Try running the code below on XCode:

Swift Code:
var control1 = "for 3 times, "
var action1 = "roast"

print(control1)
print(action1)

Console:
x3

16
© Copyright Codomo Pte Ltd 2018
Variables
String concatenation
Concatenation is another fancy word for joining strings together
(programmers really love making things sound fancy). To join
strings together, we use the ‘+’ operator. See the fourth line.

Swift Code:
var control1 = "for 3 times, "
var action1 = "roast"
var final_words = control1 + action1
print(final_words)

Console:

x3

17
© Copyright Codomo Pte Ltd 2018
Variables
Data types
There are many different data types in programming like integers,
strings, floats, booleans, arrays, tuples, bytes and many more.
We’ll only be focusing on these for this learning resource.

Data Type Expression

Integer Int

String String

Character char

Boolean bool

Type conversion
Swift includes methods to convert from one data type to another.
Run the code below to convert between string & integers.

Converting Integer to String


var x = 3 // Create a variable equals to 3
var x_str = String(x) // Convert x from Integer to String
print (x_str + " potatoes") // print out “3 potatoes”

Converting String to Integer


var x = "3" // Create a variable equals to 3
var x_int = Int(x) // onvert x from String to Integer
print (x_int! + 2) // print out 5

18
© Copyright Codomo Pte Ltd 2018
Variables (Exercise)
Getting & Updating Variable

1. Initialise a variable “x” with value 10. Then, add 5 to it. The
final value of x should print 15.
2. Initialise a variable “a” with value 10. Then, divide it by 2. The
final value of “a” should print 5.
3. Initialise a variable “b” with value 12. Then, divide it by 3.
Find the remainder.

Mathematical Operators (Predict the answer without your computer!)

var k = 20 + 10 * 20 - 20
print(k)

k = ___

var z = 100%49
print(z)
z = ___

var x = 5
x = x+1
print(x)
var y = x+10
y = 2*x+1
print(y)
x = ___
y = ___

19
© Copyright Codomo Pte Ltd 2018
Variables (Exercise)
String Concatenation

1) String a = “Hello, ”, String b = “Potato King”. Concatenate


both strings and print out “Hello, Potato King”.

Data Conversion

1) var x = “10”. Convert x to an integer, and add 20 to it. You


should get 30.
2) var y = 7. Convert y into a String and print “7 Potato Kings”.

20
© Copyright Codomo Pte Ltd 2018
For Loop
What is a for loop?
Suppose you wanted to print the word “Mash” 1000 times. How
do you do it? You can write the print statement 1000 times but
that would be a little silly. Thankfully, for loops are here to help!
For loops make repetitive tasks very easy to perform. Let’s see how
they are used in Swift.

In Potato Pirates In Swift

for i in 1...3 {
print("Mash")
}

Type this out in XCode and see what it does. When you’re done,
let’s take a closer look at each part of the code.

22
© Copyright Codomo Pte Ltd 2018
For Loop
Breakdown (for loop)
Let’s take a closer look at the structure of a for loop.

dummy variable range

for i in 1...3
Legend
Range: Loop will execute the action until condition is false
The letter “i” is a ‘dummy variable’. It is a temporary variable that exists within the loop.

Below shows the process of how a for loop will work. On the first
iteration, the variable “i” will carry the value of 1. On the next
iteration, it will increase by 1. The loop continues until the
condition is no longer met and becomes false.

Console: Iteration Value of i

1st 1

2nd 2

3rd 3

23
© Copyright Codomo Pte Ltd 2018
For Loop
Nested for loop
While playing Potato Pirates, did you try stacking several for loop
cards on top of each other? You can do the same in Swift as well
by placing for loops within other for loops, or, in programming
terms, nesting them.

In Potato Pirates In Swift


for i in 1...3 {
for j in 1...3{
print("Mash")
}
}

Loop-ception.
What a beauty!

24
© Copyright Codomo Pte Ltd 2018
For Loop
Breakdown (nested for loop)
Let’s take a closer look.

Inner Loop
for i in 1...3 {
for j in 1...3{
print("Mash")
}
}

Outer Loop
for i in 1...3 {
for j in 1...3{
print("Mash")
}
}

25
© Copyright Codomo Pte Ltd 2018
For Loop (Exercise)
Basic Questions

1) Generate the following number sequence: 1,2,3,...,100.


2) Generate the following number sequence: 3,4,..,20.

Convert Potato Pirates to Swift

1) An enemy ship has 10 potato crew


members. It is attacked by the cards on
the left. Show that there are 8 potato
crew members left.

2) The variable y represents the number of


ships you have. You have 2 ships, and
the enemy has 30 potato crew members.
Show that there are 12 potato crew
members left.

26
© Copyright Codomo Pte Ltd 2018
For Loop (Exercise)
Convert Potato Pirates to Swift

3) An enemy ship has 10 potato crew


members. It was attacked by the card on
the left, and it has 4 potatoes left. How
many cards does the enemy have?

4) Fill in the blank such that the code


below will perform the code shown on
the cards.

Code:
for i in 1...__{
enemy_crew = enemy_crew - 1;
}

27
© Copyright Codomo Pte Ltd 2018
While Loop
What is a while loop?
Just like for loops, a while loop too repeats based on a condition;
albeit with a slight difference. The loop will repeatedly execute its
action until the stated condition becomes false. Let’s find out how
they are used.

In Potato Pirates In Swift

while crew > 4 {


print (“Mash”)
}

Type the code above in XCode and see


what it does. Remember to declare the
variable “crew” before this code. When
Stop Button you’re done, let’s take a closer look at
each part of the control statement.
Note: Hit the stop button on the top bar to
stop the infinite loop

29
© Copyright Codomo Pte Ltd 2018
While Loop
Breakdown (while loop)
Let’s take a closer look at the structure of a while loop.
condition

while crew > 4


A boolean expression is one which can either take a True or False value. The
condition check of “crew > 4” returns a boolean value. The while loop will stop
running when the value returned by the condition check is false.

The example below shows how a while loop will work. The crew
begins with 7 crew members. On the first iteration, the while loop
will check if there are more than 4 crew members. Since 7 > 4 is
true, it will execute the action to reduce the crew by 2. On the
next iteration, the action will run again as 5 > 4. Finally, it stops at
the third iteration as 3 > 4 is false.

var crew = 7;
while (crew > 4) {
crew = crew - 2
}
print(crew)

Iteration Value of crew Is crew > 4? Action

1st 7 TRUE Reduce crew by 2

2nd 5 TRUE Reduce crew by 2

3rd 3 FALSE NA

30
© Copyright Codomo Pte Ltd 2018
While Loop
Comparison Operators
Comparison operators are used to compare 2 objects, and will
either return ‘true’ or ‘false’ (also known as booleans).

Comparison Operators Quick Examples


Equal to == Expression Output

Not equal != 1 == 1 TRUE

Less than < 1 != 1 FALSE

Greater than > 3<4 TRUE

Less than or equal <= 1 > 10 FALSE


to
5 <= 5 TRUE
Greater than or >=
equal to 8 >= 10 FALSE

Logical Operators
Logical operators are typically used with boolean values. When
they are, they return a boolean value. Below are some examples.

Logical Operators Quick Examples


AND && A B A && B A || B

OR || TRUE TRUE TRUE TRUE

NOT ! TRUE FALSE FALSE TRUE

FALSE TRUE FALSE TRUE

FALSE FALSE FALSE FALSE

31
© Copyright Codomo Pte Ltd 2018
While Loop
Comparison and logical operators in Swift
Below are some examples of how comparison and logical operators
are used in Swift.

Swift Code:
var crew1 = 3;
var crew2 = 5;
var isDead = false

print(crew1 == 3)
print(crew2 <= 2)
print(crew1 > crew2)
print(crew1 > crew2 && crew2 == 5)
print(crew1 > crew2 || crew2 == 5)
print(!isDead)

Console:

32
© Copyright Codomo Pte Ltd 2018
While Loop (Exercise)
Basic Questions

1) Generate this sequence of number with while loop: 10,9,...,1.


2) Generate this sequence of number with while loop: 10,9,..,5.

Predict the result (Do this without your computer!)


var crew = 20;
while crew >= 8 {
crew = crew - 1
}
print(crew)
crew = ___

var crew = 20
while crew == 10 {
crew = crew - 1;
}
print(crew)
crew = ___

33
© Copyright Codomo Pte Ltd 2018
While Loop (Exercise)
Convert Potato Pirates to Swift

1) An enemy ship has 10 potato crew


members. It was attacked by the card
deck shown on the left. Show that there
are 4 potato crew members left.

2) An enemy ship has 20 potato crew


members. It is attacked by the card deck
shown on the left. Show that there are 2
potato crew members left.

34
© Copyright Codomo Pte Ltd 2018
While Loop (Exercise)
Convert Potato Pirates to Swift

This is the
enemy

A B C

3) Which card deck can deal the highest damage to the enemy?
Convert all 3 decks into Swift code.

35
© Copyright Codomo Pte Ltd 2018
If-Else and Switch
What is an if-else statement?
If-else statements help us write programs that can make decisions!
We use if-else statements everyday in our lives:
“If you are tired, sleep; or else, keep working” or “If you are hungry,
eat; or else, skip your meal”. Can you think of one more?

In Potato Pirates In Swift

if crew <= 4 {
print ("Fry")
}
else {
print ("Mash")
}

Type the code out in XCode and see what it does. Remember to
declare the variable “crew” first. When you’re done, we’ll take a
closer look at the if statement.

37
© Copyright Codomo Pte Ltd 2018
If-Else and Switch
Breakdown (if statement)
Let’s take a closer look at the structure of an if-else statement.
condition

if crew <= 4

if crew <= 4 {
// code A
}
else {
// code B
}

Legend
Condition: A boolean expression. It will return True or False

Similar to the while loop, an if statement will execute an action


based on a condition. If a condition is true, it will run code A; else
it will run code B. It’s that simple. However, the if-else statement
differs from while loop; it only runs once.

While and For are loops, but If-Else is


a statement, so it only runs once!

38
© Copyright Codomo Pte Ltd 2018
If-Else and Switch
What is a switch statement?
A switch statement compares the value of a variable to the values
specified in case statements. It’s very similar to the if-else
statement. Let’s learn how to use it in Swift!

In Potato Pirates

Get a new ship and a potato

Pick a card from the discard pile

Draw 3 cards

In Swift
var crew = 1

switch (crew) {
case 1:
print("get a new ship and a potato")
break;
case 2:
print("pick a card from the discard pile")
break;
case 3:
print("draw 3 cards")
break;
default:
print("you get nothing")
}
39
© Copyright Codomo Pte Ltd 2018
If-Else and Switch
Breakdown (switch statement)
The switch statement value is compared with the value of each
case. If there is a match, the corresponding case is executed.
Otherwise, the default case is executed.

Closer look value

switch(crew)
General Structure
switch (crew) {
case 1:
// code A
case 2:
// code B

Default:
// code C
}

Err… where is the “break”?


Before Swift 5, break statements are used to exit a control
statement. Without it, when code in a case is executed, the code
will continue to run downwards, executing the code in other cases
even if it doesn’t match. But with Swift 5, a break statement is no
longer necessary for switch cases. Hence, no breaks!
40
© Copyright Codomo Pte Ltd 2018
If-Else and Switch (Exercise)
Convert Potato Pirates to Swift

1) An enemy ship has 10 potato


crew members. It is attacked by
the card deck shown on the left.
Show that there are 7 potato
crew members left.

2) An enemy ship has 10 potato


crew members. It is attacked by
the card deck shown on the left.
Show that there are 6 potato
crew members left.

Let’s relax the “max 3 cards in


your hand” rule for a while.
41
© Copyright Codomo Pte Ltd 2018
If-Else and Switch (Exercise)
Convert Potato Pirates to Swift

3) Create a switch statement with the following cases:


1 Potato: Print (“I am dying!”)
2 Potatoes: Print (“Am I dying?”)
3 Potatoes: Print (“I am an unlucky pirate!”)
4 Potatoes: Print (“I shall not give up!”)
5 or more Potatoes: Print (“There’s nothing to worry about.”)

42
© Copyright Codomo Pte Ltd 2018
Switch Syntax
Swift Syntax Cheat Sheet
switch (ships){
case 1:
While Loop Syntax If-else Loop Syntax
case 2: Condition
Actions

default: while (crew > 4){ Condition

} if (crew > 4) {
Action
} }
Actions
else{
For Loop Syntax Initialising Variables }
Declare Value
for i in 1...3{
//code here var crew = 10
}
Variable name

Comparison & Logical Operators Data Types


Equal == String → String
Integer → int
Not equal != Character → char
Boolean → boolean
Less than <

Type Casting
Greater than >

Integer → String Integer.toString()


Less than or equal <=

Greater than or equal >= String → Integer Integer.valueOf()

And && Character from variable.charAt()


string
Or ||

Not !

Arithmetic Operators
Addition/ Subtraction Multiplication Division Remainder
Concatenation

+ - * / %

44
© Copyright Codomo Pte Ltd 2018
Answer Sheet for Exercises
Variables

Getting & Updating Variable

1. 2. 3.
var x = 10 var a = 10 var b = 12
x = x + 5 a = a / 2 b = b / 3
print(x) print(a) print(b)

Mathematical Operators (Predict the answer without computer)


k=200, z=2, x=6 , y=13

String Concatenation

1.
var a = "Hello "
var b = "Potato King"
print(a+b)

Data Types

1.
var x = "10"
var x_int = Int(x)!
print(x_int+20)

2.
var y = 7
var y_str = String(y)
print(y_str + " Potato Kings")

45
© Copyright Codomo Pte Ltd 2018
Answer Sheet for Exercises
For loop

Basic Questions

1. 2.
for i in 1...100 { for i in 3...20 {
print(i) print(i)
} }

Convert Potato Pirates to Python

1.
var enemy_crew = 10
for i in 1...2 {
enemy_crew = enemy_crew - 1
}
print(enemy_crew)

2.
var y = 2
var enemy_crew = 30
for j in 1...3 {
for i in 1...y {
enemy_crew = enemy_crew - 3
}
}
print(enemy_crew)

3. 3
4. 11, 12, 13, 14, or 15

46
© Copyright Codomo Pte Ltd 2018
Answer Sheet for Exercises
While loop

Basic Questions
1. 2.
var crew = 10 var crew = 10
while crew >= 1 { while crew >= 5 {
print(crew) print(crew)
crew = crew - 1; crew = crew - 1
} }

Predict the result (Do this without computer)


1. crew = 7 2. crew = 20

Convert Potato Pirates to Swift


1. 2.
var enemy_crew = 10 var enemy_crew = 20
while enemy_crew > 4 { while enemy_crew > 4 {
enemy_crew = enemy_crew - 2 for i in 1...3 {
} enemy_crew = enemy_crew - 2
print(enemy_crew) }
}
print(enemy_crew)

3a. 3b.
var crew = 16 var crew = 16
while crew > 5 { for i in 1...3 {
crew = crew - 3 crew = crew - 3;
} }
print(crew) print(crew)

3c. Card deck A deals the highest


var crew = 16 damage.
for i in 1...3 {
while crew > 5 {
crew = crew - 1
}
}
print(crew)

47
© Copyright Codomo Pte Ltd 2018
Answer Sheet for Exercises
If-else

Convert Potato Pirates to Swift


1.
int enemy_crew = 10;
if (enemy_crew <= 5){
enemy_crew = enemy_crew - 2;
}
else{
enemy_crew = enemy_crew - 3;
}
System.out.println(enemy_crew);

2.
var enemy_crew = 10
if enemy_crew <= 5 {
enemy_crew = enemy_crew - 2
}
else{
enemy_crew = enemy_crew - 3
}
print(enemy_crew)

48
© Copyright Codomo Pte Ltd 2018
Answer Sheet for Exercises
If-else

Convert Potato Pirates to Swift


1.
var crew = 10
switch(crew) {
case 1:
print("I am dying!")
break
case 2:
print("Am I dying?")
break
case 3:
print("I am an unlucky pirate!")
break
case 4:
print("I shall not give up!")
break
default:
print("There's nothing to worry about.")
}

49
© Copyright Codomo Pte Ltd 2018

You might also like