O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required