Swift Basics


In the previous chapter, you learned that a variable has a content that can be changed. Sometimes, this makes a perfect sense. For example, your age changes every year, so it makes sense to create a variable age and change its content each time you have a birthday.

On the other hand, your birth date should never change as it’s constantly the same. That’s why Swift lets you create constants, assign them an initial value, which can’t be changed later, ever.

Let’s test this. In your playground, create a new variable called age and assign it your current age:

var age = 40

Below, create a new constant called birthdate and assign it the date your were born:

let  birthdate = "27.08.1981"

Now, the important part. Let’s say, you’ll return to this code one year later. To change your age, you just assign a new value to the age variable:

age = 41

However, your birth date can never change, so this code won’t work:

birthdate = "01.01.2021"

As you can see in your playground, the complier shows the error…

enter image description here

…and even offers a solution

enter image description here

However, we don’t want to make this fix, because the date you were born should stay constant, so we rather don’t attempt to change it.

« Previous: Variables Next: Types »