In almost any program that we create, we will need to store data at some point. In Swift, you can store data in two ways: variables and constants. What is the difference between these two? When do we use which?
Swift Basics
Fall 2023
In almost any program that we create, we will need to store data at some point. In Swift, we can store data in two ways: variables and constants. We can think of both variables and constants as a box holding some value inside. However, there is one key difference between these two. A variable can change its value whenever we want. On the contrary, a constant can hold a value once and can never be changed again.
It may seem pointless to have both variables and constants; however, there are many advantages. If Xcode knows that a value will never change, it will optimize our program to make it run faster. Another advantage is that if we were to make a mistake and change a value of a constant when we don’t need to, Xcode will tell us and our code will not compile.
To create a variable, we use the var keyword.
1var instructor = "Vin"
To change the value of the variable, we can simply do the following.
1var instructor = "Vin"
2instructor = "Richie"
Let’s try this in the Xcode playground.
Notice how we do not need to use the var keyword the second time. We should only use the var keyword if we are declaring a new variable. We can test this out in the Xcode playground.
Now, what if we wanted to use a constant instead of a variable? All we would need to do is to use the let keyword instead.
As we can see, changing the instructor variable to a constant caused Xcode to get angry. The error message clearly informs us that we are attempting to change the value of a constant.
VinBot
Hi!
I’m VinBot. An AI assistant here to answer your questions about Vin Bui's portfolio.
How can I help you today?
Unleash our creativity and make something extraordinary happen. Send me a message and let's explore the possibilities.