Variables
Often you want to change the data behind a name. For example, if you were keeping track of your bank account balance with deposits and withdrawals, you might use a variable rather than a constant.
If your program’s data never changed, then it would be a rather boring program! But as you’ve seen, it’s not possible to change the data behind a constant.
When you know you’ll need to change some data, you should use a variable to represent that data instead of a constant. You declare a variable in a similar way, like so:
var variableNumber: Int = 42
Only the first part of the statement is different: You declare constants using let, whereas you declare variables using var.
Once you’ve declared a variable, you’re free to change it to whatever you wish, as long as the type remains the same. For example, to change the variable declared above, you could do this:
var variableNumber: Int = 42 variableNumber = 0 variableNumber = 1_000_000
To change a variable, you simply assign it a new value.
Note: In Swift, you can optionally use underscores to make larger numbers more human-readable. The quantity and placement of the underscores is up to you.
This is a good time to take a closer look at the results sidebar of the playground. When you type the code above into a playground, you’ll see that the results sidebar on the right shows the current value of variableNumber at each line:
The results sidebar will show a relevant result for each line if one exists. In the case of a variable or constant, the result will be the new value, whether you’ve just declared a constant, or declared or reassigned a variable.