Learn Swift - Chapter 2: Constants

Constant - something that does not or cannot change or vary.

If I wanted to tell you my company's name in English it could look like this:

I work for the company Dapper Gentlemen.

Since I have told you the name of the company I work for I no longer need to tell you again. If I were to say to you "My company is going to have a booth at the next GDC conference." you would know that Dapper Gentlemen would have a booth at the conference.

The name of my company is not going to change, it will remain constant, which is why we would use a constant in Swift instead of a variable (which we will talk about in the next chapter).

In this example "the company" works the same way as a constant in Swift. The company is a term that refers to the particular value, "Dapper Gentlemen". In the same way, a constant is a word that refers to a particular value.

A constant is created when you type let followed by the name that you give it and then the value that it is equal to.

If I wanted to tell you the name of my company in Swift it could look like this:

let companyName = "Dapper Gentlemen"

It could also look like this:

let company = "Dapper Gentlemen"

or like this:

let theNameOfMyCompany = "Dapper Gentlemen"

or something else entirely. It is up to me how to name my constants.

As you can see, the constant companyName refers to the text string "Dapper Gentlemen", which means we never have to specify "Dapper Gentlemen" again. Every time swift encounters the constant companyName in the future, it will know it is a constant that refers to "Dapper Gentlemen".