When we need to store a value that should never change, we use the keyword let
. Unlike var
, which allows us to modify a variable’s value, let
creates a constant—a value that stays the same throughout the program.
In our previous post, we learned that variables can change. But sometimes, we want to make sure a value remains fixed and cannot be accidentally modified. This is where let
comes in.
Let’s understand the let keyword — what it is, why it’s useful, and how to use it with different examples.
What is let?
The let
keyword is used to create constants. A constant is like a box that you can put something in once, but once it’s inside, you can’t change it.
Syntax of let
Here’s how we declare a constant:
let constantName = value
let
tells Swift we are creating a constant.constantName
is the name we give to our constant.value
is the fixed data that the constant will store.
Unlike variables (var), once we assign a value to a let constant, you cannot change it.
Defining a Constant
Here’s an example to declare a constant:
let pi = 3.14159
print(pi) // Output: 3.14159
In this example:
- We declare pi as a constant using let.
- We assign it the value 3.14159.
- The value of pi cannot be changed later in the program.
If we try to change it, Swift will throw an error:
pi = 3.14 // Error: Cannot assign to value: 'pi' is a 'let' constant
Here are some example scenarios where the let
can be used.
Using let for fixed data
Let’s say we’re building a program that calculates a circle’s area. Since π (pi) is a fixed mathematical constant, it makes sense to use let:
let pi = 3.14159
let radius = 5
let area = pi * Double(radius) * Double(radius)
print(area) // Output: 78.53975
Here, pi and radius are constants because their values won’t change. This helps us prevent accidental modifications in our code.
Using let for user information
Imagine we have an app where a user’s date of birth never changes:
let birthYear = 1990
print("The user was born in (birthYear).")
// Output: The user was born in 1990.
Since a birth year will never change once set, let
is the perfect choice here.
Constants and Type Inference
Just like with var
, Swift can automatically figure out the type of a constant based on the assigned value:
let appName = "SwiftGuide"
Here, Swift knows that appName
is a String because we assigned it a text value. We don’t need to specify String explicitly.
Preventing Unintentional Changes
One of the biggest advantages of using let
is that it protects our data from being modified by mistake.
Consider this example with a student’s ID number:
let studentID = 12345
If we try to change it:
studentID = 67890 // Error: Cannot assign to value: 'studentID' is a 'let' constant