There is a special type of variable in Swift, which is called constant or let.
A constant is a variable that we do not want to change the value of during the whole program.
Creation:
You create a constant variable just like you create a normal one, but using the keyword let instead of var:
let ourName = "AlgoCademy"
print(ourName) // Output: AlgoCademy
Reassignment not allowed:
However, a let variable cannot be reassigned because it is constant. If you try to reassign a let variable, you'll get an error.
For example, this code:
let ourName = "AlgoCademy"
ourName = "Andy" // Here is the problem
would produce error: cannot assign to value: 'ourName' is a 'let' constant
Usage:
It seems like constants are just variables with some limitations. So, why use them when we can do the same things (and more) with normal variables?
The power of constants lies in their limitation! Constants were invented to provide some level of guarantee that the code can't change the underlying value.
This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.
Picture this: You are the first developer to have ever worked at a new startup. When you have written the core code, you created some important variables that describe your company:
let companyName = "Apple"
let foundingDate = "April 1st, 1976"
let founderName = "Steve Jobs"
Ten years later, your company blew up and you have hundreds of Software Engineers managing millions of lines of code.
I bet you wouldn't love it if a Junior Developer was able to do this successfully:
companyName = "Microsoft"
founderName = "Bill Gates"
But you are smart! You made those variables constants ten years ago and have nothing to worry about now. As for the Junior, they'll just get an error and probably a slap on the wrist by their manager.
Assignment
Follow the Coding Tutorial and let's work with constants!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.