If you go to one of the very first pages in the official documentation of the Swift Programming Language, you will find it mentions the following:

[…] Swift also makes extensive use of variables whose values can’t be changed. These are known as constants, and are much more powerful than constants in C.

I remember feeling lost reading this when I started working with Swift (almost 10 years ago!). Since I recently started revisiting C++ and C, I thought it’d be a good time to review why Constants in Swift are so powerful, and a few insights on comparing them to constants in C.

We can’t explain why constants in Swift are so powerful if we don’t understand what a constant actually is. Let’s revisit what Constants actually are and why they exist.

Constants in Swift

One of the fundamental reasons we have constants and variables in programming languages is simply because it is much easier to work with names and words than it is to work with values.

Let’s focus on this line of code:

let isJohnAnAdult = isAdult(age: johnsAge) // true

As you can see, the developer only needs to worry about calling the isAdult function, and about passing any age as parameter, the function does the rest of the work. There is no need to work with specific values like 36 or 18, which would make it very prone to errors.

We do that by using variables and constants. These allow us to assign values to names and words we can work with. If we look at the whole code:

**let** adulthoodThreshold = 18
**var** johnsAge = 36

func isAdult(age: Int) -> Bool {
  age >= adulthoodThreshold
}

**let** isJohnAnAdult = isAdult(age: johnsAge) **// true**

In this example, the isAdult function determines if a person is considered an adult by comparing it to a pre-set adulthood threshold. In this example, we’ll consider people who are 18 years or older to be adults. Depending on the age, passed as parameter, the function returns a Bool indicating whether the person’s age is is an adult (true) or not (false).

<aside> 💡 Constants and variables allow us to work with data more easily by associating a name to a value of a given type.

</aside>

Another benefit of working with constants instead of directly with values (literals), is that we can have multiple constants that have the same value and work with them independently.

var homesBuilt: Int = 7
let daysInWeek: Int = 7

If you were writing an app for a construction company, you probably want to keep track of how many homes are already built in a given neighborhood, and maybe try to calculate how many you can build in a week. More houses can be built in a neighborhood, but it would be very confusing for everyone else if you to write an app that uses a 9-day week!

The main difference between a variable and a constant is that constants guarantee that the value will not be reassigned.