Constants
Take a look at this:
let number: Int = 10
This declares a constant called number which is of type Int. Then it sets the value of the constant to the number 10.
Note: Thinking back to operators, here’s another one. The equals sign, =, is known as the assignment operator.
The type Int can store integers. The way you store decimal numbers is like so:
let pi: Double = 3.14159
This is similar to the Int constant, except the name and the type are different. This time, the constant is a Double, a type that can store decimals with high precision.
There’s also a type called Float, short for floating point, that stores decimals with lower precision than Double. In fact, Double has about double the precision of Float, which is why it’s called Double in the first place. A Float takes up less memory than a Double but generally, memory use for numbers isn’t a huge issue and you’ll see Double used in most places.
Once you’ve declared a constant, you can’t change its data. For example, consider the following code:
let number: Int = 10 number = 0
This code produces an error:
Cannot assign to value: 'number' is a 'let' constant
In Xcode, you would see the error represented this way:
Constants are useful for values that aren’t going to change. For example, if you were modeling an airplane and needed to keep track of the total number of seats available, you could use a constant.
You might even use a constant for something like a person’s age. Even though their age will change as their birthday comes, you might only be concerned with their age at this particular instant.