Day 3

Values of Constant and Variables

Did you find the online compilers in the previous blog and tried to execute the codelines?

Time to explain some basics of Swift. If you are a beginner read on, if your not an absoute beginner in Swift programming then you may familiar with the next two lines of code.

let year = 2019

print("Hello world, hello \(year)"

Fixed and variable values

In the first line you create a variable named year and give it a value 2019. Easy but thats not all. the variable is given the value 2019 and this value cannot changed anymore, it has a fixed value. The variable has a fixed value and is a socalled constant, This is all done with the keyword let. But how do we create a variable that can be changed? We have to use the keyword var.

var anotherYear = 2019

Experiment

Try to change the value of year to 2020

Change the value of anotherYear to 2020

Changing a value is easy, just use the name of the variable and give it another value.

year = 2020 or anotherYear = 2020

You will see error messages and your program will not run while trying to change the value of a constant.

Only once

By using the var and let keywords your program can use the variables or constants. But befor your program can use them they have to be announced, thats called declared.

If you eventually made a mistake by setting the value of anotherYear to a different value by declaring it again var anotherYear = 2020 you noticed some errors.

A variable or constant cannot be declared more then once otherwise your program will not run.

 

Experiment

Declare the variable anotherYear or the constant year again

var anotherYear = 2021 or var year = 2020, just try some more different combinations

There is more to say about the first line of Swift code and thats all about the type of the variable or constant but thats for later. See you next blog.

 

Share this Post