Constants vs Variables

We said that types describe the nature of the data held by a constant or variable. What, then, are constants and variables? Up to now, you have only seen variables. Variables’ values can vary, which means that you can assign them a new value. You varied numberOfStoplights’s value in this code: numberOfStoplights += 2.

Often, however, you will want to create instances with values that do not change. Use constants for these cases. As the name indicates, the value of a constant cannot be changed.

You made numberOfStoplights a variable, and you changed its value. But what if you did not want to vary the value of numberOfStoplights? In that case, making numberOfStoplights a constant would be better. A good rule ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.