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
let is block-scoped. var is function scoped. let does not allow to redeclare variables. var allows to redeclare variables.
This is because both instances are treated as different variables since they have different scopes. This fact makes let a better choice than var . When using let , you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.
Swift employs the keywords let and var for naming variables. The let keyword declares a constant, meaning that it cannot be re-assigned after it's been created (though its variable properties can be altered later). The var keyword declares a new variable, meaning that the value it holds can be changed at a later time.
In swift, we use the var keyword to declare a variable. Swift uses variables to store and refer to values by identifying their name.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With