Software, Tech & Coding simplified.

What is the Difference between Let and Var in Swift?

In Swift, there are two types of values:

  • Constants. These are immutable variables.
  • Variables. These are mutable variables.

To declare constants/variables in Swift:

  • let is used to declare an immutable constant. You cannot change the value of it later.
  • var is used to create a mutable variable that you can change later.

For example, to create a constant value in Swift, use the let keyword:

let num = 100.0

And to create a variable in Swift, use the var keyword:

var x = 200

Swift advises you to create constants whenever possible. You can see this in action when Xcode shows you warnings 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.

Further Reading

Swift – Upgrade Your Skills with These 5 Tips

iOS Development Tips in 2021

Share

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email