Intro to Variables and Constants in Swift

·

3 min read

Being able to store, reference and manipulate different types of data, is a fundamental part of computer programming. This data could be anything such as username, game score, the status of a checkbox, height of a cell etc.

Variables

Variables allow us to temporarily store values in our program. They also give us the ability to manipulate this data. Let’s have a look at this example.

var message = “Welcome to my world!”

We use the keyword var to create a variable called message. The variable stores the value “Welcome to my world!”.

You can give your variable any name you like. In the above example, I gave my variable the name “message”, however, you can call it message1, response, xyz, abracadabra, etc.

var message = "Welcome to my world!"
var message1 = "Welcome to my world!"
var response = "Welcome to my world!"
var xyz = "Welcome to my world!"
var abracadabra = "Welcome to my world!"

It's a good practice to give your variables a meaningful name so that anyone reading your code can understand the purpose of the variable.

Now if we want to change the message to “Welcome to my beautiful universe!”, we can do the following:

var message = "Welcome to my world!"
message = "Welcome to my beautiful universe!"

Note that we do not need to use the keyword var this time. The keyword var is only used when we want to create the variable. Once it is created we can assign it a different value, if we need to.

Constants

In swift, we store our data as a variable or a constant. The only difference between the two methods of storage is that we can change the value of a variable, however, the value of a constant can not be changed once set.

Let’s have a look at how we create a constant.

let username = “monkey”

To create a constant we use the keyword let. If you now try to change the value of this constant, you will see an error message.

let username = “monkey”
username = "lion"

You will see the following error message appear:

Cannot assign to value: ‘username’ is a ‘let’ constant

This can be quite useful if you want to store a value that never needs to be changed. For example, if you want to store the name of a file you want to fetch, you can store it as a constant.

The rule of thumb is to always use a constant rather than a variable unless you are sure that you will need to modify the value.

Before you go...

I hope you found this article useful. Follow me on Twitter to get tips on iOS development and programming in general.