Swift is the language behind every lesson from here on. In the next four lessons we learn it on its own, before we put it inside an app. You can practise in an Xcode Playground or in a small Command Line Tool project, or in the free Swift Playgrounds app. Pick whichever starts fastest. Each example prints its answer with print, so you can see what it does.
let and var
Swift has two ways to give a name to a value. Use let for a constant, a value that never changes after you set it. Use var for a variable, a value you will change later. Prefer let whenever you can. Swift even warns you when a var is never changed. It is a small habit that prevents many bugs, because a value that cannot change cannot be changed by mistake.
let name = "Asha"
var score = 10
score = score + 5
print("\(name) has \(score) points")
Swift works out the type by itself, which is called type inference. Here name is a String and score is an Int. You can also write the type on purpose, with a colon: let price: Double = 4. This is useful when the number should be a decimal even though you typed a whole number.
The special part in the print line is \(name). A backslash followed by brackets inside a string drops a value into the text. This is called string interpolation, and you will use it all the time.
The main types
Intis a whole number such as 42.Doubleis a decimal number such as 3.14. UseDoublefor ordinary decimals in this course.Stringis text.Boolistrueorfalse.- Swift will not mix types by itself.
IntplusDoubleis an error until you convert one:Double(score) + 2.5. This is strict on purpose, and it catches mistakes before the app runs. - Money needs care. A
Doublecannot hold some decimal values exactly, so real finance apps use theDecimaltype. We useDoublein the course to keep the code short, and the Expense Tracker lesson says so again.
Arrays and dictionaries
An array is an ordered list of values of one type. A dictionary keeps pairs, a key and a value, and you look up a value by its key.
var expenses: [Double] = [12.5, 40, 7.25]
expenses.append(19.99)
print(expenses.count) // 4
print(expenses[0]) // 12.5, counting starts at zero
var limits: [String: Double] = ["Food": 200, "Travel": 150]
limits["Fun"] = 80
print(limits["Food"] ?? 0) // 200.0
Notice that looking up limits["Food"] gives an *optional* value, because the key might not exist. The ?? 0 part says *use zero if there is nothing*. Optionals are so important that lesson 5 is all about them.
Making decisions: if and switch
Use if to choose between paths. The conditions do not need brackets, but the braces are required. Use switch when one value can match many cases. A switch in Swift must cover every possible case, so the compiler warns you if you forget one.
let total = 120.0
if total > 100 {
print("Over budget")
} else if total > 50 {
print("Careful")
} else {
print("All good")
}
let day = 3
switch day {
case 1: print("Monday")
case 2: print("Tuesday")
case 3...5: print("Midweek")
default: print("Another day")
}
The pattern 3...5 is a range that includes 3, 4 and 5. The range 0..<5 stops before 5. Both are very common in loops.
Repeating work: loops
let items = ["Coffee", "Bus", "Lunch"]
for item in items {
print("Spent on \(item)")
}
for i in 1...3 {
print("Round \(i)")
}
var n = 3
while n > 0 {
print(n)
n -= 1
}
A for loop walks through a list or a range. A while loop repeats as long as a condition is true, so be sure something inside it changes, or it never ends. You will use for much more than while.
Common beginner mistakes
- Changing a
letconstant. Swift stops you with an error. Change it tovaronly if the value really must change. - Forgetting that array counting starts at 0. The first item is
items[0], and asking for an index that does not exist crashes the program. - Mixing
IntandDoublein one sum. Convert withDouble(x). - Writing
=when you mean==. One stores a value. Two compare.
Your task
- Create a Playground or a command line project.
- Make an array of five expense amounts and use a
forloop to add them into avar total. - Print
Over budgetif the total is above 100 andWithin budgetotherwise. - Make a dictionary of three category names and limits, and print each one with string interpolation.
How to check it worked
- Your total is right when you add the numbers by hand.
- Changing one amount changes the message when it crosses 100.
- You can say the difference between
letandvarand whyletis the better first choice.