Learn/Swift/2. Values and variables
Lesson 2 of 8
Sign in

Swift, lesson 2

Values and variables

A program that only prints fixed text is not very useful. To work with data you need to store values and give them names. Swift has two ways to do that.

let and var

  • let makes a constant: you set its value once and it can never change.
  • var makes a variable: you can give it a new value later.

Swift's advice is simple: use let by default and switch to var only when you really need to change the value. Constants make code easier to follow, because once you have read the line that sets one, you know its value for good. The compiler even warns you when a var is never changed.

Types

Every value in Swift has a , and a name keeps the same type for its whole life. The ones you will use most:

2 exercises to try what you just read.

Exercise 1

Pet profile

Press Ctrl Enter or Check to test your code.

Exercise 2

Coin collector

Press Ctrl Enter or Check to test your code.

type
TypeHoldsExample
Intwhole numbers42, -7
Doublenumbers with a fractional part3.14, -0.5
Booltrue or falsetrue
Stringtext"Swift"

Usually you do not write the type at all. Swift infers it from the starting value: 42 becomes an Int, 4.5 becomes a Double. When you want to be explicit, add a type annotation with a colon:

Because types are fixed, you cannot store text in an Int variable, and Swift will not mix Int and Double in one calculation on its own. You convert explicitly by calling the type like a function. Converting a Double to an Int chops off the fraction, it does not round.

Naming

Swift names use lowerCamelCase: start lowercase, then capitalise each new word, as in highScore or daysUntilLaunch. Names cannot start with a digit or contain spaces. Pick names that say what the value means; temperature beats t.

You can declare several names on one line by separating them with commas:

String interpolation

To put a value inside a string, write a backslash followed by the value in parentheses: \(value). Swift converts the value to text for you, and you can put whole expressions inside.

Interpolation is usually clearer than gluing pieces together with +, and it works for any type, not just strings.

Further reading

  • The Basics: constants, variables, types and conversion
  • Strings and Characters: string interpolation

The starter declares four constants about a pet. Print them as a profile using string interpolation, exactly like this:

The program reads no input. Use the constants, don't retype their values.

A game character starts with 0 coins. Use a var called coins and update it step by step:

  1. Pick up 5 coins.
  2. Pick up 12 more.
  3. A bonus doubles the coins.
  4. Spend 4 coins on a potion.

After that, print Coins: followed by the total. Then print the average coins per level as a Double, given that the player has finished 4 levels (store that in a let). Convert with Double(...) before dividing.

Expected output:

let planet = "Mars"
var fuel = 100
fuel = 80        // fine: fuel is a variable
// planet = "Venus"  // compile error: planet is a constant
let lives: Int = 3
var speed: Double = 12   // 12 is stored as 12.0 because of the annotation
let isOnline: Bool = false
let apples = 3
let price = 0.5
let cost = Double(apples) * price   // 1.5
let whole = Int(9.99)               // 9
var x = 0, y = 0
let name = "Ada"
let age = 36
print("\(name) is \(age) years old.")        // Ada is 36 years old.
print("Next year she will be \(age + 1).")   // Next year she will be 37.
Name: Biscuit
Age: 3 years
Weight: 4.5 kg
Vaccinated: true
Coins: 30
Per level: 7.5