Skip to content

Variables

Think of a Variable as a Box

A variable is like a box where you can put something inside, but you can change what’s inside the box whenever you want! Unlike a constant, which is fixed, a variable can hold different things at different times.

How a Box is Used

  • Imagine you have a box that you can fill with toys. One day, you put a ball inside the box, but the next day, you decide to put a robot inside it instead.

  • Similarly, in programming, a variable holds a value that you can change later. You can keep putting different things into the same box (or variable), and it will always be able to hold a new value.


How to Declare a Variable in Swift

In Swift, we use the keyword var to define a variable. Here's an example:

Let’s say you want to store your age in a variable. Your age might change as you get older, right?

So, we use a variable to store it.

var age = 6
In this example:

  • var means this is a variable—something that can change.
  • age is the name of the variable.
  • 6 is the value that the variable holds, but you can change it as you get older!

For example, if your age changes from 6 to 7 next year, you can update it:

age = 7

Now, the variable age holds the value 7 instead of 6.

Examples of Variables

Social and Practical Variables
  • Your Pocket Money (because it can change as you spend or receive money)

    var pocketMoney = 5.00 // 5 dollars
    pocketMoney = 10.00    // After receiving more money
    pocketMoney = 8.00 // After spending something worth 2.00
    
Software Engineering Variables
  • User's Score in a game (it changes as the player earns more points)

    var userScore = 0
    userScore = 100   // After earning points
    
  • Current Temperature (it changes depending on the weather)

    var temperature = 70
    temperature = 85   // It's warmer now
    
Mathematical Variables
  • Your Total Savings (it changes as you add or subtract money)

    var savings = 50.00
    savings = 75.00 // After adding more money
    
  • Distance Traveled (it changes as you move)

    var distanceTraveled = 0
    distanceTraveled = 10  // After walking 10 meters
    distanceTraveled = 20  // After walking more
    

Key Points to Remember

  • A variable holds something that can change.
  • You use var in Swift to create a variable.
  • A variable is like a box you can fill with different things whenever you want!