Variables and constants are the foundations of every programming language and Swift is no different. They can simply be seen as references.
So ,what’s the difference between variables and constants?
Each time we declare something, we will either need to declare it as a variable or a constant. So how do we know what to choose?
It’s very simple…
Declaring a constant means that the value can be declared only once and cannot be changed, contrary to the variables that allow changes after the initial declaration.
How do we declare a variable and a constant in Swift?
In Swift, a constant is declared using the keyword “let”, while a variable is declared using the keyword “var”, as it can be seen in the example here below:
let answer = 1
var grade = 0
We have declared “answer” as a constant and we gave it the value of 1. This means that “answer” will always be equal to 1 and cannot be changed afterwards. Trying to do so, will result in an error in Swift.
On the contrary, “grade” has for the moment the value of 0 and we are allowed to change its value afterwards if we need to.
You can even declare multiple constants or variables on the same line. To do so, you simply separate them by a comma:
let a = 1, b = 2, c = 3
var d = 0, e = 100
Some things you cannot do:
- Swift is very sensitive about the space you put between the name, the equal sign and the value. Indeed, you need to either have the same space on both sides of the equal sign or no space. You cannot have a space on the left side of the equal sign and no space on the right side, this will result in an error.
- You cannot declare a constant and a variable on the same line. Indeed, when declaring multiple values on the same line, they all need to be of the same type: either constants or variables.
Now that we have seen the 2 main classes, let’s look at the different types of variables and constants that exist in Swift.
Why and when would you use constants?
I bet the question going through your head now, is when would you use a constant in Swift and also why… Well, there are 2 reasons, why Swift programming needs constants:
- It will increase your performance because your compiler will know which variables change and which are not
- It adds safety to your code. Indeed, there is no sense in adding complexity to your code if you know that a value will remain the same. This can avoid errors later on.
So don’t be shy and use “let” anytime you know a value won’t change.