Constants refer to values that will not change in the program. In a constant, you set the value only once and never change during the execution.
You can think of a constant as a special kind of variable whose value will never be changed.
In Swift programming, the
let keyword is used to create a constant. After whitespace, you have to type the name of the constant.
Below is the syntax of declaring constant:
let nameOfConstant = <initial value>
Let’s see with an example:
let color = "Green" print(color)
The output of the above code:
In the code, we have created a constant and then print it in the terminal.
Well, let’s see what if you try to change the value of the constant:
The above code is written in the Xcode Swift playground. As you can see, it is telling “Cannot assign to value: ‘color’ is a ‘let’ constant“. So it is proven that constant value can not be modified after you declare it once.
You can set the data type in the time of declaring a constant just like you can do in the case of creating a variable.
Below is given the syntax:
var nameOfConstant:<data type> = <optional initial value>
Below is the example where we set a type annotation:
// Set constant data type let myPoint: Float = 7.84673 print(myPoint) // See another example let color: String = "Green" print(color)
There are certain rules you have to follow during giving a name to the constant. It can be composed of letters, digits, and the underscore character.
The name of a constant must begin with a letter or with an underscore.
Swift 4 and all the upper versions are case-sensitive. So upper and lowercase letters in the name of constant will treat differently. Below is an example:
let color = "Green" let Color = "Red"
In the above example, color and Color will become two different constants.
You may think why someone is going to use constants in Swift instead of using variables. Not only you, but many of the beginners programmers also think so. This is because variables and constants are the same.
The only difference is that value of a constant will never be changed, but the value of a variable can be changed in the program.
Though variables and constants work as same in real-life projects in the program and it will not change the working of the program, but still it is better and a good practice to use constants instead of variables.
In your program, if a value should never change in the lifetime of the program, then it is useful to use a constant in that case. Thus it will show an error if you mistakenly change the value.
Using constant is useful also when there are many programmers working on the same project. If somebody tries to change the value of a constant or try to redefine it, then it will show a warning.
Using constant instead of variable is also great for the readability of the code.
A programmer who reads the code will understand from constant that the value will never be modified or changed in the lifetime of the program.