It is important to know the differences between variables and constants. These are things you will use every day and luckily, it’s really simple to understand. Choosing the correct declaration (var or let) when creating objects makes your code safer and it encourages you to know your code inside and out.
Declaring an object as a variable or constant is not only for integer values (as shown on this page), the same also apply to other types like strings, integers, arrays and dictionaries.
In Swift, var means variable. A variable is an object that can be mutated, or changed.
In our example code below, we create an object named interestRate. We declare it as a variable by adding “var” before the name. Because we declared it a variable, this object can be updated whenever our interest rate changes.
var interestRate = 4.4 //Creates the interestRate variable and assigns it an initial value of 4.4.
Now, since in our example, the interest rate fluctuates often, we need to update this variable with the new rate.
interestRate = 4.6
If we use the println command, we can see that the value of interestRate has increased to 4.6.
println(interestRate) //Prints "4.6" to the console.
In Swift, let means constant. Constant means the the value assigned to the object can never be changed. Once it is set, it’s done. You use a constant when you need to set a value that will never change.
In our example, our interest rate is fixed, once it is created it never needs updating. Because of this, we choose to declare interestRate as a let instead of var.
let interestRate = 4.5
If we try to update or otherwise modify this object, it will result in an error.
interestRate = 4.7 //Results in an error because it is not a variable.