Swift 101 - let vs var

Welcome, to the first blog in my Swift 101 series!

Today I’ll be explaining the difference between let and 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!

Both let and var are used when defining variables. You can think of variables as bags of information which can hold a number, true or false, even some text, like "Hello, World!"

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 var.

//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.

 Takeaway Tip

The Swift compiler is there to help and will prompt you when to use let and var when defining variables, it will even suggest when to change a variable from let to var and vice versa.

An image showing a let variable having its value changed (mutated)

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.

Happy Swifting!

 
5
Kudos
 
5
Kudos

Now read this

Swift 101 - nil

This is a super quick blog to go over the Swift keyword - nil. nil is described in the Apple docs as: meaning “the absence of a valid object.” Not the easiest thing to understand if you’re starting out, right? If you’re new to... Continue →