Start learning free

LESSON 13 OF 415 · VARIABLES

Constants in Swift: Declaring Values with let

Lesson Read the full explanation

There is a special type of variable in Swift, which is called constant or let.

A constant is a variable that we do not want to change the value of during the whole program.


Creation:

You create a constant variable just like you create a normal one, but using the keyword let instead of var:

let ourName = "AlgoCademy"

print(ourName) // Output: AlgoCademy

Reassignment not allowed:

However, a let variable cannot be reassigned because it is constant. If you try to reassign a let variable, you'll get an error.

For example, this code:

let ourName = "AlgoCademy"

ourName = "Andy" // Here is the problem

would produce error: cannot assign to value: 'ourName' is a 'let' constant


Usage:

It seems like constants are just variables with some limitations. So, why use them when we can do the same things (and more) with normal variables?

The power of constants lies in their limitation! Constants were invented to provide some level of guarantee that the code can't change the underlying value.

This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.

Picture this: You are the first developer to have ever worked at a new startup. When you have written the core code, you created some important variables that describe your company:

let companyName = "Apple"
let foundingDate = "April 1st, 1976"
let founderName = "Steve Jobs"

Ten years later, your company blew up and you have hundreds of Software Engineers managing millions of lines of code.

I bet you wouldn't love it if a Junior Developer was able to do this successfully:

companyName = "Microsoft"
founderName = "Bill Gates"

But you are smart! You made those variables constants ten years ago and have nothing to worry about now. As for the Junior, they'll just get an error and probably a slap on the wrist by their manager.


Assignment
Follow the Coding Tutorial and let's work with constants!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · VARIABLES

    Constants in Swift, explained

    What a constant is

    A constant is a name bound to a value that cannot change after it is set. You declare one like a variable, but with the keyword let instead of var:

    let companyName = "Acme"
    print(companyName)
    
    Acme
    

    Reading a constant works exactly like reading a variable. You can print it, use it in calculations and interpolate it into strings. The only thing you cannot do is assign to it again.

    What happens when you try to change one

    let ourName = "Acme"
    ourName = "Andy"
    
    error: cannot assign to value: 'ourName' is a 'let' constant
    note: change 'let' to 'var' to make it mutable
    

    This is a compile-time error, so the program never starts. The same applies to compound operators: with let maxLives = 3, the line maxLives += 1 fails with left side of mutating operator isn't mutable: 'maxLives' is a 'let' constant.

    Why limit yourself?

    A constant looks like a variable with fewer abilities, and that is the point. When you see let, you know the value is the same everywhere it is used, so you do not have to scan the rest of the code for places that might change it. In a large program with many authors, the compiler enforces that promise.

    Use let for anything that is set once: a company name, the value of pi, the maximum number of lives in a game. Use var only for values that must change, such as a score or a counter. Swift programmers write let by default and switch to var when the compiler or the design demands it.

    The exercise, step by step

    The starter code declares pi as a constant, then tries to overwrite it:

    let pi = 3.14
    
    pi = 5.0
    
    print(pi)
    

    Because pi is a let, the line pi = 5.0 is rejected and the program cannot be built. The goal is to print 3.14, so the fix is to delete that line.

    1. Find the reassignment pi = 5.0.
    2. Delete it. Do not change let to var: that would compile but print 5.0, and the value of pi was meant to be fixed.
    3. Keep the declaration and the print line exactly as they are.

    The solution in Swift

    let pi = 3.14
    
    
    
    print(pi)
    

    The program prints 3.14. The blank lines left by the deleted line are harmless.

    Swift details

    • The value is not always known upfront. A constant may be declared first and assigned once later, as in let later: Int followed by later = 5. It can be assigned only once, and the type must be written because there is no value to infer from.
    • A constant collection cannot be modified. With let list = [1, 2], calling list.append(3) fails with cannot use mutating member on immutable value: 'list' is a 'let' constant.
    • The type is still inferred. let pi = 3.14 is a Double.
    • Naming. Constants follow the same camelCase naming as variables. Swift has no ALL_CAPS convention for them.

    Common mistakes

    • Changing let to var just to silence the error. Ask whether the value should change first.
    • Using var for everything. A var that is never changed suggests a value that might change when it does not.
    • Assuming let hides a value. You can read a constant anywhere it is in scope.

    Key takeaways

    • let declares a constant that cannot be reassigned.
    • Assigning to a constant is a compile-time error, so mistakes are caught before the program runs.
    • Default to let and use var only when a value has to change.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free