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 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
var value can be change, after initialize. But let value is not be change, when it is intilize once.
In case of var
function variable() {
var number = 5, number = 6;
console.log(number); // return console value is 6
}
variable();
In case of let
function abc() {
let number = 5, number = 6;
console.log(number); // TypeError: redeclaration of let number
}
abc();
Let is an immutable variable, meaning that it cannot be changed, other languages call this a constant. In C++ it you can define it as const.
Var is a mutable variable, meaning that it can be changed. In C++ (2011 version update), it is the same as using auto, though swift allows for more flexibility in the usage. This is the more well-known variable type to beginners.
var is variable which can been changed as many times you want and whenever
for example
var changeit:Int=1
changeit=2
//changeit has changed to 2
let is constant which cannot been changed
for example
let changeit:Int=1
changeit=2
//Error becuase constant cannot be changed
Even though you have already got many difference between let and var but one main difference is:
let is compiled fast in comparison to var.
let
is used to declare a constant value - you won't change it after giving it an initial value.
var
is used to declare a variable value - you could change its value as you wish.