Suppose we are building a game, and we want to keep track of the player’s name, the player’s score that goes from 0 to 10, the player’s level, etc. We need some variables!
Before we can use a variable, we must declare, or create, it.
So to declare a variable called
score and set it equal to
0, we need to write:
var score = 0
varis a keyword used to declare variables.
scoreis the name of the variable.
=is the assignment operator.
0is the value of the variable.
In Swift, a single equal sign
= means to “assign” values (not compare). In the code above, we are assigning the
score variable a value of
So now, we can print out the value of the variable
The output would be:
Note: Variable names should be in camelCase format.
Declare a variable named
year with a value of the current year.