Explain the difference between let and var in Swift


This article will explain the difference between let and var in the Swift language.

Most of the time, we deal with different data types in any programming language. However, we need to identify values by name. These names are called variables.

Like C, Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values can’t be changed. These are known as constants. They are more powerful than constants in C. Constants are used throughout Swift to make code safer and clearer in intent. This is because you work with values that don’t need to change.

In the Swift language, there are two types of value

  • Constants − These are immutable values.

  • Variables − These are mutable values.

Mutable Vs Immutable

Those values can be changed after the declaration in Swift, as they are variables. These can never be changed, they are immutable

How to declare variables in Swift?

We use the keyword let to denote a constant. The value of a constant cannot be changed later.

We use the variable keyword to define the variable content. You can change the value of the variable later.

Example

How to declare a constant?

let studentName = "Arpit Mishra"

You can see we used the keyword let here. Since this value cannot be changed in the future, we declared it as a constant.

How to declare a variable?

var grade = 7

By using the var keyword, we define a variable of type Int. It is a variable value, not a constant because it might change in the future.

Differences between let and var

let var
Called constants also. Called variables also.
These are immutable. These are mutable.
We use the let keyword to define a constant. We use the var keyword to define a variable.
The let keyword cannot be applied to lazy properties. The var keyword is required for lazy properties.

Conclusion

Swift advises you to create constants whenever possible. You can see this in action when Xcode warns you about using var.

Using constant values is meaningful when you want to declare variables that are not supposed to change. When you make them constants using the let keyword, it is impossible to accidentally change them in the future.

Updated on: 09-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements