1.7. Constants

So far, we talked about variables. Just as a refresher, you can always change the values of a variable, maintaining the type-safety. However, in many cases, you would not want a value to be changeable and keep it unchanged while the program runs. These are called constants.

To write a constant in Swift, you need to use the keyword let. You write, let variableName : DataType = value. (Recall Type annotations?)

For example, let's add the following line of code in our Playground:

let myConstant:Int = 14
print("My constant is \(myConstant)")

It will output the following:

My constant is 14

Now, let's try to set a new value 20 to myConstant.

myConstant = 20

But now you will see the following error:

So, myConstant is not changeable (not mutable).

**Please note: when you will be building iOS apps, **use constants as much as possible. It is suggested that you should declare everything as constants using let and then selectively change them to variables when needed.

Last updated