You are on page 1of 32

1 - How to create variables and constants

Swift gives us two ways of storing data, depending on whether you want the data to
change over time.

var greeting = "Hello, playground"

When you make a variable, you can change it over time:

var name = "Ted"


name = "Rebecca"
name = "Keeley"

Now, when we use let we make a constant, which is a value that can’t change.

let character = "Daphne"


character = "Eloise"
character = "Francesca"

we could print out the value of a variable each time it’s set

var playerName = "Roy"


print(playerName)

playerName = "Dani"
print(playerName)

playerName = "Sam"
print(playerName)

the style is called “camel case”,


let managerName = "Michael Scott"
let dogBreed = "Samoyed"
let meaningOfLife = "How many roads must a man walk down?"

2 - How to create strings


let actor = "Denzel Washington"

let quote = "Then he tapped a sign saying \"Believe\" and walked away."

let movie = """


A day in
the life of an
Apple engineer
"""

First, you can read the length of a string by writing .count after the name of the variable
or constant:
print(actor.count)

You don’t need to print the length of a string directly if you don’t want to – you can
assign it to another constant, like this:
let nameLength = actor.count
print(nameLength)

The second useful piece of functionality is uppercased(), which sends back the same
string except every one of its letter is uppercased:
print(result.uppercased())

he last piece of helpful string functionality is called hasPrefix(), and lets us know
whether a string starts with some letters of our choosing:
print(movie.hasPrefix("A day"))

here’s also a hasSuffix() counterpart, which checks whether a string ends with some text:
print(filename.hasSuffix(".jpg"))
3 - How to store whole numbers

For example, we could create a score constant like this:


let score = 10
Of course, you can also create integers from other integers, using the kinds of arithmetic
operators that you learned at school: + for addition, - for subtraction, * for multiplication,
and / for division.
let lowerScore = score - 2
let higherScore = score + 10
let doubledScore = score * 2
let squaredScore = score * score
let halvedScore = score / 2
print(score)

For example, this creates a counter variable equal to 10, then adds 5 more to it:
var counter = 10
counter = counter + 5

Rather than writing counter = counter + 5, you can use the shorthand operator +=,
which adds a number directly to the integer in question:
counter += 5
print(counter)

what does exactly the same thing, just with less typing. We call these compound
assignment operators, and they come in other forms:
counter *= 2
print(counter)
counter -= 10
print(counter)
counter /= 2
print(counter)

So, we could ask whether 120 is a multiple of three like this:


let number = 120
print(number.isMultiple(of: 3))
4 - How to store decimal numbers

This storage method causes decimal numbers to be notoriously problematic for


programmers, and you can get a taste of this with just two lines of Swift code:
let number = 0.1 + 0.2
print(number)
If you want that to happen you need to tell Swift explicitly that it should either treat the
Double inside b as an Int:
let c = a + Int(b)

Or treat the Int inside a as a Double:


let c = Double(a) + b

So:
let double1 = 3.1
let double2 = 3131.3131
let double3 = 3.0
let int1 = 3

Combined with type safety, this means that once Swift has decided what data type a
constant or variable holds, it must always hold that same data type. That means this code
is fine:
var name = "Nicolas Cage"
name = "John Travolta"

But this kind of code is not:


var name = "Nicolas Cage"
name = 57
Finally, decimal numbers have the same range of operators and compound assignment
operators as integers:
var rating = 5.0
rating *= 2

5 - How to join strings together


you can join them together into a new string just by using +, like this:
let firstPart = "Hello, "
let secondPart = "world!"
let greeting = firstPart + secondPart
You can do this many times if you need to:
let people = "Haters"
let action = "hate"
let lyric = people + " gonna " + action
print(lyric)

Think about this for example:


let luggageCode = "1" + "2" + "3" + "4" + "5"
Swift can’t join all those strings in one go. Instead, it will join the first two to make “12”,
then join “12” and “3” to make “123”, then join “123” and “4” to make “1234”, and
finally join “1234” and “5” to make “12345” – it makes temporary strings to hold “12”,
“123”, and “1234” even though they aren’t ultimately used when the code finishes.

For example, we could create one string constant and one integer constant, then combine
them into a new string:
let name = "Taylor"
let age = 26
let message = "Hello, my name is \(name) and I'm \(age) years old."
print(message)

You see, using + lets us add strings to strings, integers to integers, and decimals to
decimals, but doesn’t let us add integers to strings. So, this kind of code is not allowed:

let number = 11
let missionMessage = "Apollo " + number + " landed on the moon."

You could ask Swift to treat the number like a string if you wanted, like this:

let missionMessage = "Apollo " + String(number) + " landed on the moon."

It is still both faster and easier to read to use string interpolation:

let missionMessage = "Apollo \(number) landed on the moon."

Tip: You can put calculations inside string interpolation if you want to. For example, this
will print “5 x 5 is 25”:

print("5 x 5 is \(5 * 5)")


Making a Boolean is just like making the other data types, except you should assign an
initial value of either true or false, like this:
let goodDogs = true
let gameOver = false

You can also assign a Boolean’s initial value from some other code, as long as ultimately
it’s either true or false:

let isMultiple = 120.isMultiple(of: 3)

To try this out, try making gameOver a variable and modifying it like this:

var gameOver = false


print(gameOver)

gameOver.toggle()
print(gameOver)

6 - How to store ordered data in arrays


Let’s start with some simple examples of creating arrays:
var beatles = ["John", "Paul", "George", "Ringo"]
let numbers = [4, 8, 15, 16, 23, 42]
var temperatures = [25.3, 28.2, 26.4]

So, we could read some values out from our arrays like this:
print(beatles[0])
print(numbers[1])
print(temperatures[2])
If your array is variable, you can modify it after creating it. For example, you can
use append() to add new items:
beatles.append("Adrian")

And there’s nothing stopping you from adding items more than once:
beatles.append("Allen")
beatles.append("Adrian")
beatles.append("Novall")
beatles.append("Vivian")

contains one type of data at a time. So, this kind of code isn’t allowed:
temperatures.append("Chris")

Swift won’t let you mix these two different types together, so this kind
of code isn’t allowed:
let firstBeatle = beatles[0]
let firstNumber = numbers[0]
let notAllowed = firstBeatle + firstNumber
You can see this more clearly when you want to start with an empty array and add items
to it one by one. This is done with very precise syntax:
var scores = Array<Int>()
scores.append(100)
scores.append(80)
scores.append(85)
print(scores[1])

You can make other kinds of array by specializing it in different ways, like this:
var albums = Array<String>()
albums.append("Folklore")
albums.append("Fearless")
albums.append("Red")
Arrays are so common in Swift that there’s a special way to create them: rather than
writing Array<String>, you can instead write [String]. So, this kind of code is exactly
the same as before:
var albums = [String]()
albums.append("Folklore")
albums.append("Fearless")
albums.append("Red")

Swift’s type safety means that it must always know what type of data an array is storing.
That might mean being explicit by saying albums is an Array<String>, but if you
provide some initial values Swift can figure it out for itself:
var albums = ["Folklore"]
albums.append("Fearless")
albums.append("Red")

var characters = ["Lana", "Pam", "Ray", "Sterling"]


print(characters.count)
characters.remove(at: 2)
print(characters.count)
characters.removeAll()
print(characters.count)
Third, you can check whether an array contains a particular item by using contains(), like
this:
let bondMovies = ["Casino Royale", "Spectre", "No Time To Die"]
print(bondMovies.contains("Frozen"))

Fourth, you can sort an array using sorted(), like this:


let cities = ["London", "Tokyo", "Rome", "Budapest"]
print(cities.sorted())
Finally, you can reverse an array by calling reversed() on it:
let presidents = ["Bush", "Obama", "Trump", "Biden"]
let reversedPresidents = presidents.reversed()
print(reversedPresidents)

For example, here’s an array containing an employee’s details:


var employee = ["Taylor Swift", "Singer", "Nashville"]
I’ve told you that the data is about an employee, so you might be able to guess what
various parts do:
print("Name: \(employee[0])")
print("Job title: \(employee[1])")
print("Location: \(employee[2])")

we could rewrite our previous example to be more explicit about what each item is:
let employee2 = ["name": "Taylor Swift", "job": "Singer", "location": "Nashville"]

If we split that up into individual lines you’ll get a better idea of what the code does:
let employee2 = [
"name": "Taylor Swift",
"job": "Singer",
"location": "Nashville"
]

When it comes to reading data out from the dictionary


print(employee2["name"])
print(employee2["job"])
print(employee2["location"])
Optionals are a pretty complex issue that we’ll be covering in detail later on, but for now
I’ll show you a simpler approach: when reading from a dictionary, you can provide a
default value to use if the key doesn’t exist.
Here’s how that looks:
print(employee2["name", default: "Unknown"])
print(employee2["job", default: "Unknown"])
print(employee2["location", default: "Unknown"])

For example, we could track which students have graduated from school using strings for
names and Booleans for their graduation status:
let hasGraduated = [
"Eric": false,
"Maeve": true,
"Otis": false,
]

Or we could track years when Olympics took place along with their locations:
let olympics = [
2012: "London",
2016: "Rio de Janeiro",
2021: "Tokyo"
]

print(olympics[2012, default: "Unknown"])

You can also create an empty dictionary using whatever explicit types you want to store,
then set keys one by one:
var heights = [String: Int]()
heights["Yao Ming"] = 229
heights["Shaquille O'Neal"] = 216
heights["LeBron James"] = 206
For example, if you were chatting with a friend about superheroes and supervillains, you
might store them in a dictionary like this:
var archEnemies = [String: String]()
archEnemies["Batman"] = "The Joker"
archEnemies["Superman"] = "Lex Luthor"
How to use sets for fast data lookup
they are similar to arrays, except you can’t add duplicate items,

First, here’s how you would make a set of actor names:


let people = Set([" Washington", " Cruise", " Cage", " L Jackson"])

If you’re curious how the set has ordered the data, just try printing it out:
print(people)

The second important difference when adding items to a set is visible when you add
items individually. Here’s the code:
var people = Set<String>()
people.insert("Denzel Washington")
people.insert("Tom Cruise")
people.insert("Nicolas Cage")
people.insert("Samuel L Jackson")

How to create and use enums


So, we could rewrite our weekdays into a new enum like this:
enum Weekday {
case monday
case tuesday
case wednesday
case thursday
case friday
}

Now rather than using strings, we would use the enum. Try this in your playground:
var day = Weekday.monday
day = Weekday.tuesday
day = Weekday.friday

you can just write case once, then separate each case with a comma:
enum Weekday {
case monday, tuesday, wednesday, thursday, friday
}
skip the enum name after the first assignment, like this:
var day = Weekday.monday
day = .tuesday
day = .friday

How to use type annotations


So far we’ve been making constants and variables like this:
let surname = "Lasso"
var score = 0

Type annotations let us be explicit about what data types we want, and look like
this:
let surname: String = "Lasso"
var score: Int = 0

For example, maybe score is a decimal because the user can get half points, so
you’d write this:
var score: Double = 0

String holds text:


let playerName: String = "Roy"
Int holds whole numbers:
var luckyNumber: Int = 13

Double holds decimal numbers:


let pi: Double = 3.141

Bool holds either true or false:


var isAuthenticated: Bool = true

Array holds lots of different values, all in the order you add them. This must be
specialized, such as [String]:
var albums: [String] = ["Red", "Fearless"]

Dictionary holds lots of different values, where you get to decide how data should be
accessed. This must be specialized, such as [String: Int]:
var user: [String: String] = ["id": "@twostraws"]

Set holds lots of different values, but stores them in an order that’s optimized for
checking what it contains. This must be specialized, such as Set<String>:
var books: Set<String> = Set(["The Bluest Eye", "Foundation", "Girl,
Woman, Other"])

Knowing all these types is important for times when you don’t want to provide initial
values. For example, this creates an array of strings:
var soda: [String] = ["Coke", "Pepsi", "Irn-Bru"]

============================================================
End
7 - condition
How to check a condition is true or false

if someCondition {
print("Do something")
}

Well, let’s try the score example: if a score constant is over 80, let’s print a message.
Here’s how that would look in code:
let score = 85

if score > 80 {
print("Great job!")
}

Let’s try it out – what do you think this code will print?
let speed = 88
let percentage = 85
let age = 18

if speed >= 88 {
print("Where we're going we don't need roads.")
}

if percentage < 85 {
print("Sorry, you failed the test.")
}

if age >= 18 {
print("You're eligible to vote")
}

but they also work equally well with strings right out of the box:
let ourName = "Dave Lister"
let friendName = "Arnold Rimmer"

if ourName < friendName {


print("It's \(ourName) vs \(friendName)")
}

if ourName > friendName {


print("It's \(friendName) vs \(ourName)")
}

The first is == and means “is equal to,” which is used like this:
let country = "Canada"

if country == "Australia" {
print("G'day!")
}

The second is !=, which means “is not equal to”, and is used like this:
let name = "Taylor Swift"

if name != "Anonymous" {
print("Welcome, \(name)")
}

How to check multiple conditions


Using else we could rewrite our previous code to this:
let age = 16
if age >= 18 {
print("You can vote in the next election.")
} else {
print("Sorry, you're too young to vote.")
}

Here’s how that looks:


let a = false
let b = true

if a {
print("Code to run if a is true")
} else if b {
print("Code to run if a is false but b is true")
} else {
print("Code to run if both a and b are false")
}

This has two conditions, so we could write this:


let temp = 25

if temp > 20 {
if temp < 30 {
print("It's a nice day.")
}
}

So, we could change our code to this:


if temp > 20 && temp < 30 {
print("It's a nice day.")
}

must have permission from a parent. We could write that using || like so:
let userAge = 14
let hasParentalConsent = true

if userAge >= 18 || hasParentalConsent == true {


print("You can buy the game")
}

Here’s the code for that:


enum TransportOption {
case airplane, helicopter, bicycle, car, scooter
}

let transport = TransportOption.airplane

if transport == .airplane || transport == .helicopter {


print("Let's fly!")
} else if transport == .bicycle {
print("I hope there's a bike path…")
} else if transport == .car {
print("Time to get stuck in traffic.")
} else {
print("I'm going to hire a scooter now!")
}

How to use switch statements to check multiple


conditions

enum Weather {
case sun, rain, wind, snow, unknown
}

let forecast = Weather.sun

if forecast == .sun {
print("It should be a nice day.")
} else if forecast == .rain {
print("Pack an umbrella.")
} else if forecast == .wind {
print("Wear something warm")
} else if forecast == .rain {
print("School is cancelled.")
} else {
print("Our forecast generator is broken!")
}

So, we can replace all those if and else if checks with this:
switch forecast {
case .sun:
print("It should be a nice day.")
case .rain:
print("Pack an umbrella.")
case .wind:
print("Wear something warm")
case .snow:
print("School is cancelled.")
case .unknown:
print("Our forecast generator is broken!")
}

For example, we could switch over a string containing a place name:


let place = "Metropolis"

switch place {
case "Gotham":
print("You're Batman!")
case "Mega-City One":
print("You're Judge Dredd!")
case "Wakanda":
print("You're Black Panther!")
default:
print("Who are you?")
}

We could make a simple approximation of this song using fallthrough. First, here’s how
the code would look without fallthrough:
let day = 5
print("My true love gave to me…")
switch day {
case 5:
print("5 golden rings")
case 4:
print("4 calling birds")
case 3:
print("3 French hens")
case 2:
print("2 turtle doves")
default:
print("A partridge in a pear tree")
}

How to use the ternary conditional operator for


quick tests
For example, we could create a constant called age that stores someone’s age, then create
a second constant called canVote that will store whether that person is able to vote or
not:
let age = 18
let canVote = age >= 18 ? "Yes" : "No"

enum Theme {
case light, dark
}

let theme = Theme.dark

let background = theme == .dark ? "black" : "white"


print(background)

End
8 - loop

How to use a for loop to repeat work

Let’s start with something simple: if we have an array of strings, we can print each string
out like this:
let platforms = ["iOS", "macOS", "tvOS", "watchOS"]

for name in platforms {


print("Swift works great on \(name).")
}

Swift has a similar-but-different type of range that counts up to but excluding the final
number: ..<. This is best seen in code:
for i in 1...5 {
print("Counting from 1 through 5: \(i)")
}

for i in 1..<5 {
print("Counting 1 up to 5: \(i)")
}

Here’s a basic while loop to get us started:


var countdown = 10

while countdown > 0 {


print("\(countdown)…")
countdown -= 1
}
print("Blast off!")

9 - functions
print("Welcome to my app!")
print("By default This prints out a conversion")
print("chart from centimeters to inches, but you")
print("can also set a custom range if you want.")

func showWelcome() {
print("Welcome to my app!")
print("By default This prints out a conversion")
print("chart from centimeters to inches, but you")
print("can also set a custom range if you want.")
}

Call the function as shown in the example below, and it will perform it.

func myInfo() {

var age = 18
let name = "Krishna"
var line = ("Hi, I am " + "\(name) \n") + ("I am " + "\(age)")
print(line)

myInfo()

Parameters
parameter in the code written inside the parenthesis of a function.
func appleProduct(product: String) {

print("\(product)" + " is an Apple product")

appleProduct(product: "iPhone 13")


func tesla(model: String, year: Int) {

print("Tesla" + " \(model)" + " was released in the year" + " \(year)")
}

tesla(model: "Roadster", year: 2018)

Return Values
"Return" in programming means returning a value. The function receives the value from
what you entered, but it can also return the value by giving it back to you.

func circleArea(radius: Double) -> Double {

let pi = 3.14
var formula = pi*radius*radius

return formula

let answer = circleArea(radius: 3.5)


print(answer)

What's the position of the argument label in a function syntax?


To simply answer it, the argument labels are just written before the
parameter names and leave a space in between.

func marvel(year: Int, spiderman movie: String) {

print("\(movie) was released in \(year)")

marvel(year: 2021, spiderman: "Spider-Man: No Way Home")

Excluding Argument Labels


You can drop giving the name to an argument label by replacing it with a "_"
(underscore). For example,
func marvel(_ year: Int, spiderman movie: String) {

print("\(movie) was released in \(year)")


}

marvel(2021, spiderman: "No Way Home")

Default Parameter Values


Try remembering how you assigned a value to a variable at a time of declaring,

For example,
func demoFunction(x : Int, y : Int = 5) {
print("Parameter without Default Value = \(x)")
print("Parameter with Default Value = \(y)")
}

demoFunction(x: 3)
demoFunction(x: 3, y: 8)

10 - How to create your own structs


Swift’s structs let us create our own custom, complex data types, complete with their own
variables and their own functions.

struct Album {
let title: String
let artist: String
let year: Int

func printSummary() {
print("\(title) (\(year)) by \(artist)")
}
}

At this point, Album is just like String or Int – we can make them, assign values, copy
them, and so on. For example, we could make a couple of albums, then print some of
their values and call their functions:

let red = Album(title: "Red", artist: "Taylor Swift", year: 2012)


let wings = Album(title: "Wings", artist: "BTS", year: 2016)

print(red.title)
print(wings.artist)

red.printSummary()
wings.printSummary()
11 - classes
override func printSummary() {

print("I'm a developer who will sometimes work \(hours) hours a day, but other
times spend hours arguing about whether code should be indented using tabs or
spaces.")

You might also like