Swift Basics


Your playground has three lines of code now. You can ignore the first two for now, but focus on the third line where you can see the declaration of a variable.

A variable is like a storage where you keep some values. This storage is called a variable because its content can vary which means that you can reuse or change it. You’re probably familiar with the word variability.

A variable is a way of saving a value (a piece of information) with a specific name. By naming a value, we can later recall and reuse that value again in our code. We can also easily change that value throughout our code.

With variables we can start using a very important programming concept: repetition. This means that instead of writing out the same piece of information every time we need it, we store it in a variable, our computer remembers it and can repeat it back.

Our code creates such a variable:

var str = "Hello, playground"

This new variable is called str and its value is “Hello, playground”.

Now, click the tiny arrow below the code to execute it:

enter image description here

On the right of the playground you’ll see “Hello, playground” in the output area. This is how you know that the value has been set for our variable:

enter image description here

And because the str is a variable we can change it:

str = "Have a nice day"

Notice that this time, we don’t use the var keyword. That because the str has already been created and we are just changing its value now:

enter image description here

« Previous: Introduction Next: Constants »