Swift Variables: Let, Var, and the Difference between Them

Updated: February 22, 2023 By: Khue Post a comment

When you’re writing code in Swift, you’ll come across 2 keywords that are used to declare variables: var and let. These keywords may seem similar at first glance, but they have a few key differences that can affect your code in important ways.

Var

In Swift, the var keyword is used to declare mutable variables, which means their values can be changed after they are declared.

Example:

var myVariable = "Sling Academy"
myVariable = "Some other value"
print(myVariable)

Output:

Some other value

The first value of myVariable is Sling Academy, but it is changed to Some other value.

Variables with no initial values

In Swift, you can also use var to declare a variable with no initial value. This is useful when you want to declare a variable but don’t yet know its initial value or when you want to declare a variable and set its value later on in your code.

Example:

import Foundation

// declare a variable with an explicit data type
// but no assign an initial value
var thisYear: Int   

let currentDate = Date()
let calendar = Calendar.current
thisYear = calendar.component(.year, from: currentDate)

print(thisYear)

Output:

2023

Let

The let keyword is used to declare constants, which are values that cannot be changed after they are set. Any attempt to do so will result in a compile-time error.

Example:

let moutain = "Flame Peak"
mountain = "Flame Peak"

When this code gets executed, you will see the error message below:

Error: Cannot assign to value: 'mountain' is a 'let' constant

Note for JavaScript veterans: If you’ve worked with JavaScript before, the let keyword in Swifit can confuse you. In Swift, let declares a constant that cannot be reassigned, while in JavaScript, let declares a variable that can be reassigned later.

You might be asking what does the existence of let mean? Why not use var in all cases?

Using let to declare constants can make your code more robust and easier to reason about. If you know that a value will never change once it has been set, declaring it as a constant using let can help catch errors earlier and more easily.

Final Words

The main difference between var and let is that var is used to declare mutable variables, while let is used to declare constants. In other words, var allows you to change the value of a variable later on in your code, while let does not.