0
0
Swiftprogramming~5 mins

Why let and var distinction matters in Swift

Choose your learning style9 modes available
Introduction

Using let and var helps you control if a value can change or not. This makes your code safer and easier to understand.

When you want to store a value that should never change, like a constant number or name.
When you need to change a value later, like a score in a game or a user's input.
When you want to avoid mistakes by accidentally changing values that should stay the same.
When you want your code to be clearer about which values are fixed and which can change.
Syntax
Swift
let constantName = value
var variableName = value

let creates a constant, which means the value cannot be changed after it is set.

var creates a variable, which means the value can be changed later.

Examples
This creates a constant pi that always holds 3.14.
Swift
let pi = 3.14
// pi cannot be changed later
This creates a variable score that starts at 0 and can be changed.
Swift
var score = 0
score = 10
// score can be updated
Use let for fixed values like name, and var for values that change like age.
Swift
let name = "Alice"
// name cannot be changed

var age = 25
age = 26
Sample Program

This program shows how let keeps maxPlayers fixed, while var allows currentPlayers to change.

Swift
let maxPlayers = 4
var currentPlayers = 1
print("Max players allowed: \(maxPlayers)")
print("Current players: \(currentPlayers)")

// Trying to change maxPlayers will cause an error
// maxPlayers = 5 // Uncommenting this line will cause a compile error

// We can change currentPlayers
currentPlayers = 3
print("Updated current players: \(currentPlayers)")
OutputSuccess
Important Notes

Trying to change a let constant after setting it will cause a compile error.

Use let by default to make your code safer. Only use var when you really need to change the value.

Summary

let is for values that never change.

var is for values that can change.

Choosing the right one helps prevent bugs and makes your code easier to read.