Swift Level 1
Swift Level 1
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
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.
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
5
© Copyright Codomo Pte Ltd 2018
Getting Started
Installation of Development Platform
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
OR
Swift Playground
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!”.
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.
var crew:Int = 10
var crew:Int = 10
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”.
let crew:Int = 10
Initialising a
constant let crew:Int = 10
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:
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.
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:
BODMAS
Order Multiplication: * Subtraction: -
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.
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.
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.
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
Data Conversion
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.
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.
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.
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.
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
26
© Copyright Codomo Pte Ltd 2018
For Loop (Exercise)
Convert Potato Pirates to Swift
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.
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
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)
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).
Logical Operators
Logical operators are typically used with boolean values. When
they are, they return a boolean value. Below are some examples.
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
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
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?
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
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
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.
switch(crew)
General Structure
switch (crew) {
case 1:
// code A
case 2:
// code B
…
Default:
// code C
}
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
} 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
Type Casting
Greater than >
Not !
Arithmetic Operators
Addition/ Subtraction Multiplication Division Remainder
Concatenation
+ - * / %
44
© Copyright Codomo Pte Ltd 2018
Answer Sheet for Exercises
Variables
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)
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)
} }
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
} }
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)
47
© Copyright Codomo Pte Ltd 2018
Answer Sheet for Exercises
If-else
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
49
© Copyright Codomo Pte Ltd 2018