In Swift, variables are used to hold values that might change while the program is running. When we use the var
keyword, we are saying: I’m creating a container that can hold a value, and I might change that value later on.
You might think of a variable as a box. Once you put something inside it (like a number or a word), you can take it out, change it, or even replace it with something completely different. You use the var keyword to create that box.
Syntax of var
Here’s how you create a variable using var
:
var name = "Alice"
var
is the keyword that tells Swift we’re creating a variable.name
is the name of the variable (like labeling your box “name”)."Alice"
is the value inside the box (the thing you’re storing).
In this case, we have created a variable named name
and stored the value “Alice” inside it.
Changing the value of a variable
One of the key features of variables is that you can change their value later on. Let’s see how this works:
var name = "Alice"
name = "Bob"
print(name) // Output: Bob
In this example:
- We first set
name
to “Alice”. - Then, we change
name
to “Bob”. - When we
print
the value ofname
, it now shows Bob because the value has been updated.
What if we don’t specify a type?
In Swift, you don’t always need to tell the computer what type of value your variable will hold. Swift can figure it out for you. This is called type inference.
Here’s an example where we don’t need to specify the type of the variable:
var age = 25
You might notice that we didn’t say var age: Int = 25
. Swift automatically understands that age is a number (an integer) based on the value 25 that we assigned to it. Swift can figure out that age should be an integer.
This makes things simpler for beginners, and you don’t always need to worry about the details of types.
Using Variables with Different Data Types
Variables don’t just have to store numbers. They can store all sorts of data! For example, we can store a string (text) inside a variable:
var greeting = "Hello, World!"
print(greeting) // Output: Hello, World!
Here, we’re storing the text "Hello, World!"
in a variable called greeting
.
You can even use variables to store booleans, which are true or false values:
var isRaining = false
print(isRaining) // Output: false
Reassigning Values
You can change the value of a variable as many times as you want. Let’s look at another example:
var temperature = 22
temperature = 30
temperature = 18
print(temperature) // Output: 18
In this example, we first set temperature
to 22
, then changed it to 30
, and finally changed it again to 18
. The value of temperature
keeps changing as the program runs.