Link Menu Expand Document

Swift Programming

Variables Series · Lesson 5

Variables vs Constants

Learn when data should remain fixed with constants and when it should stay editable with variables.

Swift Programming Xcode iOS

What to focus on while watching

  • Use let for values that should not change.
  • Use var when updates are expected in your app flow.
  • Defaulting to constants can reduce accidental state changes.

Lesson Notes and Walkthrough

By now you know how to create variables. This lesson answers the next key question: Should this value be changeable or fixed?

Core Rule

  • Use let when the value should stay the same.
  • Use var when the value needs to change over time.

Simple Comparison

let appName = "BudgetBuddy"   // fixed
var currentBalance = 120.0    // can change

currentBalance = 95.5

How to Decide as a Beginner

  1. Ask: “Will this value ever change after setup?”
  2. If no, start with let.
  3. If yes, use var.

Why Prefer let by Default

  • It prevents accidental changes.
  • It makes your code easier to reason about.
  • It reduces bugs in larger projects.

Common Mistake

Beginners often declare everything with var. A better habit is to start with let, then switch to var only when the compiler tells you a reassignment is needed.


You may also like

Practice: Variables vs Constants

~5 min Beginner

Goal: Use let for fixed values and var for changing values.

Steps

  1. Declare app name as a constant.
  2. Declare user score as a variable and update it.
  3. Print both to verify behavior.

Expected Output

SwiftQuest score: 15
Need a hint? Use let appName = "SwiftQuest" and update var score.

Code

import Foundation

let appName = "SwiftQuest"
var score = 10
score = 15

print("\(appName) score: \(score)")