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 :

For constants, you use the keyword  let:

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

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.

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.

References

Image: @ Makaule / Shutterstock.com

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon