Swift Constants


title: Constants

Constants

A constant associates a name with a value of a particular type.

Example:

let name = "Chris Lattner"

You declare constants with the let keyword then give it a name name then you use an assignment operator = to assign the value "Chris Lattner" to the constant name.

Once you have declared a constant you don’t need to use the let keyword anymore you just call it by its name.

The value of a constant can’t be changed once it’s set. With that being said, it is important to note that the Swift compiler is smart enough to understand the difference between declaring a constant, and assigning a value to it. Consider the following code snippet:

let shouldWaterFreeze: Bool // (1) if temperature < 0 { shouldWaterFreeze = true // (2) else { shouldWaterFreeze = false // (3) }

The snippet above is valid and compiles with no problems (given that we have declared and assigned an Int value to temparature somewhere earlier). Notice that we declare the constant in (1), and then assign a value to it (2) or (3).

More Information:

This article needs improvement. You can help improve this article. You can also write similar articles and help the community.