Menu
Coddy logo textTech

Let vs Var

Part of the Fundamentals section of Coddy's Swift journey — lesson 4 of 86.

In Swift, you use let and var to store values.

var creates a variable — its value can be changed later:

var score = 10
print(score)  // 10
score = 20
print(score)  // 20

let creates a constant — its value cannot be changed once set:

let name = "Alice"
print(name)  // Alice
// name = "Bob"  // Error! Cannot assign to 'let' constant

When to use which?

  • Use let by default. If a value doesn't need to change, make it a constant.
  • Use var only when you know the value will need to change.

This is a best practice in Swift that makes your code safer and easier to understand.

challenge icon

Challenge

Beginner

Create a constant called language with the value "Swift" and a variable called age with the value 25. Print both values on separate lines.

Cheat sheet

Use var to create a variable (value can be changed):

var score = 10
score = 20  // OK

Use let to create a constant (value cannot be changed):

let name = "Alice"
// name = "Bob"  // Error!

Best practice: Use let by default. Only use var when the value needs to change.

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals