Start learning free

LESSON 4 OF 415 · WELCOME TO SWIFT

Variables in Swift: let, var and Types

Lesson Read the full explanation

In computer science, data is anything that is meaningful to the computer. Swift provides a large number of data types, the most frequently used being:

  • Int - represents integer numbers like 3 and -12
  • Double - represents floating point numbers like 3.14
  • Character - represents a single character like 'a', 'Z' or '?'
  • String - represents a sequence of characters like "John Doe"
  • Bool - represents one of two values: true or false

For example, computers distinguish between numbers, such as the number 12, and strings, such as "12", "dog", or "123 cats", which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.

Variables are containers for storing values. A piece of information / data lives in memory and we use a variable to store and descriptively label that data.


Variable declaration:

To create / declare a variable, we use let (for a value that won't change) or var (for a value that can change), followed by the variable's name and, optionally, its data type after a colon, like so:

let name: String = "AlgoCademy"

creates a String constant named name. A constant declared with let can't be reassigned later; one declared with var can.


Variable initialization:

We can initialize a variable to an initial value in the same line as it is created using the assignment operator (=). This code:

let name = "AlgoCademy"

creates a new String constant named name and assigns it an initial value of "AlgoCademy".

When executing this code, Swift will allocate some memory, then it will store the string "AlgoCademy" in that memory and finally will attach this name label to that memory location.

You can think of this memory location as a box. In that box, we put string "AlgoCademy". Then, we put the label name on this box.


Accessing values in variables:

Now we can use this label anywhere in our program to access the value in that box. We can print it for example:

// We create and initialize two variables:
var name = "AlgoCademy"
var age = 10

// We access the variables:
print(name)
print(age)

The output of this code is:

AlgoCademy
10

Important notice:

We almost never want to create a variable without initializing it! It's a bad coding practice and can create a lot of problems.


Assignment
Follow the Coding Tutorial and let's create some variables.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · WELCOME TO SWIFT

    Variables in Swift, explained

    Data and types

    Data is anything meaningful to the computer: a number, a word, a yes-or-no answer. Swift groups data into types. The ones you will meet first are:

    • Int, for whole numbers such as 3 and -12;
    • Double, for numbers with a fractional part such as 3.14;
    • String, for text such as "John Doe";
    • Character, for a single character such as "a" or "?";
    • Bool, for true or false.

    Types matter because they decide what you can do with a value. You can add two numbers, but 12 the number and "12" the text are different things, and Swift will not mix them silently. A Character is written with double quotes like a string, and you ask for it with a type annotation: let initial: Character = "M". Single quotes are not used for text in Swift.

    Variables and constants

    A variable is a name attached to a value stored in memory. You can picture a box with a label: the value is inside, the name is on the outside. Anywhere in your program, you use the name to get the value back.

    Swift gives you two ways to declare one:

    • let creates a constant, whose value is fixed once it is set.
    • var creates a variable, which you can reassign later.

    Use let by default, and switch to var only for values that really change. The compiler helps by warning about a var that is never changed.

    Declaring and initialising

    A declaration has the keyword, the name, an optional type annotation after a colon, and an initial value after =:

    let name: String = "AlgoCademy"
    var age: Int = 10
    

    The name comes first and the type follows it. You can usually leave the annotation out, and Swift infers the type from the value:

    let pi = 3.14
    let inferred = 42
    print(type(of: pi), type(of: inferred))
    
    Double Int
    

    Using a variable

    Write the name wherever you want the value, for example inside print:

    var name = "AlgoCademy"
    var age = 10
    print(name)
    print(age)
    
    AlgoCademy
    10
    

    To put a variable inside text, use string interpolation:

    print("\(name) is \(age)")
    
    AlgoCademy is 10
    

    Reassigning

    To change a var, assign again with = and without the keyword. The variable already exists, so writing var again would declare it a second time and cause an error:

    var age = 30
    age = 31
    age += 1
    print(age)
    
    32
    

    What the compiler rejects

    • Reassigning a constant. After let name: String = "A", the line name = "B" fails with an error that says you cannot assign to name because it is a let constant.
    • Wrong type. After var age: Int = 30, the line age = "31" fails with cannot assign value of type 'String' to type 'Int'. The same happens for age = 31.5, which is a Double.
    • Using a variable before it has a value. var x: Int followed by print(x) is an error: the variable is used before being initialised. Swift allows a declaration without a value only if every path assigns it before it is read, so give values at declaration whenever you can.
    • Declaring the same name twice. A second let x = 6 in the same scope is an invalid redeclaration.
    • Case. Names are case-sensitive: age and Age are different, and a misspelling makes the compiler say it cannot find the name in scope.

    The exercise

    The exercise has three steps, one line each:

    1. Declare the constant name with let, annotate it as String and set it to "Michael".
    2. Declare the variable age with var, annotate it as Int and set it to the number 30, with no quotes.
    3. Reassign age to 31, with no var in front.
    let name: String = "Michael"
    var age: Int = 30
    age = 31
    

    Key takeaways

    • A variable is a name for a value.
    • let makes a constant and var makes something you can change.
    • The type annotation follows the name after a colon, and it is optional when the value makes the type clear.
    • Every value has a type, and Swift will not assign a value of one type to a variable of another.
    • Give a variable its value when you declare it.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free