Swift Basics: let, var, Types, if, switch and Loops

iOS App Development with Swift and SwiftUI: Beginner to Job-Ready Projects · Swift Basics · 5 min read · Updated

let and var

  1. let creates a constant. Once it is set, Swift will not let you change it.
  2. var creates a variable. You can give it a new value later.
  3. Swift works out the type of each name and checks every use.
  4. print shows the result in the console, with values dropped into the text.

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

  • Int is a whole number such as 42. Double is a decimal number such as 3.14. Use Double for ordinary decimals in this course.
  • String is text. Bool is true or false.
  • Swift will not mix types by itself. Int plus Double is 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 Double cannot hold some decimal values exactly, so real finance apps use the Decimal type. We use Double in 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 let constant. Swift stops you with an error. Change it to var only 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 Int and Double in one sum. Convert with Double(x).
  • Writing = when you mean ==. One stores a value. Two compare.

Your task

  1. Create a Playground or a command line project.
  2. Make an array of five expense amounts and use a for loop to add them into a var total.
  3. Print Over budget if the total is above 100 and Within budget otherwise.
  4. 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 let and var and why let is the better first choice.

Frequently asked questions

Should I use let or var?

Start with let. Change to var only when the value really has to change. Swift will warn you when a var is never changed.

Why does Swift not allow Int plus Double?

Swift is strict about types so mistakes show up when you build the app and not when a user runs it. Convert on purpose, for example with Double(count).

Do I need a Mac to practise Swift?

For the language alone, no, because Swift also runs on other systems. For the app lessons you need Xcode on a Mac.