Link Menu Expand Document

Swift Programming

Variables Series · Lesson 1

How to Think About Variables

Build a mental model for variables as named containers that hold and update values in your app.

Swift Programming Xcode iOS

What to focus on while watching

  • A variable gives data a clear name so your code is easier to read.
  • Values can change over time, which makes variables useful for app state.
  • Good variable names improve both debugging and collaboration.

Lesson Notes and Walkthrough

A variable is a named storage location for data. In plain language, it is like a labeled box: you put a value in, and later you can read it or replace it with a new value.

Why Variables Matter

  • They let your app remember information such as a username, score, or message.
  • They make code easier to read because names describe what data means.
  • They allow values to change as users interact with your app.

Basic Swift Syntax

var variableName = value

Example: var score = 0
Here, var means the value can change, score is the name, and 0 is the starting value.

Step-by-Step Walkthrough

  1. Create a variable and give it an initial value.
  2. Update the variable when something changes.
  3. Print the value to verify your logic.
var points = 10
points = 15
print(points)

Output: 15

Naming Tips for Beginners

  • Use clear names: userName is better than x.
  • Use camelCase in Swift: totalPrice, isLoggedIn.
  • Name by meaning, not type. Prefer cartCount over int1.

Common Mistakes to Avoid

  1. Forgetting to use var when you plan to change the value later.
  2. Using vague names that make code hard to understand.
  3. Changing too many variables in one place without checking output.

Quick check: if the value may change, start with var. If it should never change, use let (covered in Part 5).


You may also like

Practice: Variables Basics

~5 min Beginner

Goal: Create a variable, update it, and print the result.

Steps

  1. Create a variable called message.
  2. Update the value once to simulate app state changing.
  3. Print the final value in the console.

Expected Output

Welcome back, coder!
Need a hint? Start with var message = "Hello, coder!", then assign a new value before printing.

Code

import Foundation

var message = "Hello, coder!"
message = "Welcome back, coder!"

print(message)