Ghostboard pixel

Constants In Swift

Constants In Swift

In Swift there are two types of values: constants and variables. This is very common for a programming language – however, there is one important difference in using constants in Swift.

Hint: This post has been updated to Swift 3

Constants vs variables

If you want to declare a value, it can be either a variable or a constant. For variables, you use the keyword var :

var aVariable = 5

For constants, you use the keyword let:

let aConstant = 5

Variables can change their value any time, whereas constants can only get a value assigned once:

aVariable = 10
aConstant = 10 //CompilerError

When to use constants in Swift?

This leads us to one important question: When to use constants? The answer is simple: You should always use constants whenever it is possible! The reason for that is, that non-intentional changes of the value are not possible, if it is a constant. And that can happen quickly by accident!

In other programming language it is best practice to use capital letters for constants. However, there is one simple reason why this leads to a rarer usage of constants: If you are starting with a constant and you see after same time that it must be a variable, you need to refactor your code because the name of the variable must be changed!

But in Swift it is NOT best practice to use capital letters for constants. Instead they should look just like variables. This gives you the opportunity to start with a constant, if you are not sure whether it should be a constant or a variable. If you see then that it is not avoidable for the value to be a variable, you can simply change this by replacing the keyword let with var. In the end you will use constants much more frequently.

[thrive_text_block color=”blue” headline=”Conclusion”]The convention of not using capital letters for constants can feel a little bit strange at first. However, if you give it a try, you will see the advantages.[/thrive_text_block]


Image: @ Makaule /