What is the difference between `let` and `var` in Swift?

What is the difference between let and var in Apple’s Swift language?

In my understanding, it is a compiled language but it does not check the type at compile time. It makes me confused. How does the compiler know about the type error? If the compiler doesn’t check the type, isn’t it a problem with production environment?

This error is given when I try to assign a value to a let:

Cannot assign to property: ‘variableName’ is a ‘let’ constant
Change ‘let’ to ‘var’ to make it mutable

32 Answers
32

The let keyword defines a constant:

let theAnswer = 42

The theAnswer cannot be changed afterwards. This is why anything weak can’t be written using let. They need to change during runtime and you must be using var instead.

The var defines an ordinary variable.

What is interesting:

The value of a constant doesn’t need to be known at compile time, but you must assign the value exactly once.

Another strange feature:

You can use almost any character you like for constant and variable
names, including Unicode characters:

let 🐶🐮 = "dogcow"

Excerpts From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329


Community Wiki

Because comments are asking for adding other facts to the answer, converting this to community wiki answer. Feel free edit the answer to make it better.

Leave a Comment