Swift 101 - let vs var
Welcome, to the first blog in my Swift 101 series!
Today I’ll be explaining the difference between
var, two fundamental
keywords in the Swift programming language. If you’re just getting started with Swift this is a great place to start learning as you’ll be using these two a lot!
var are used when defining variables. You can think of variables as bags of information which can hold a number,
false, even some text, like
let is used for defining constants - variables which do not change their value, for example, the number of months in a year:
let numberOfMonths = 12
var is used for defining mutable variables - variables which do change their value, for example, the temperature of a room:
var roomTemperature = 21.5
Let’s take a look an example:
Your favourite coffee shop
Imagine we run a coffee shop where we have a limited number of chairs and tables and lots of customers coming and going. We would define the number of chairs using a
let, as there is a fixed number of chairs and this cannot change. The number of customers, however, does change and is defined as a
//Start of the day let numberOfChairs = 25 var numberOfCustomers = 0 //Open the shop doors and 5 customers arrive numberOfCustomers = numberOfCustomers + 5 // The number of customers is now 5. Therefore the numberOfCustomers must be a mutable variable.
The Swift compiler is there to help and will prompt you when to use
var when defining variables, it will even suggest when to change a variable from
var and vice versa.
As a rule of thumb, I always define my variables as
let and let (pun-clang!) the compiler complain if I mutate the variable later!
Get the playground for this blog here.