var greeting = "Hello, playground"
There are four main pieces to the syntax above.
var
– This is a keyword, and its telling swift to create a new variable.greeting
– This is what we are naming our variable. We can name it whatever we want it to be; however, it should be descriptive in some way.=
– This equal sign is called the assignment operator. This is what is assigning our new variable to the value we are giving it. You aren’t required to have spacing on both sides of the equal sign; however, the spacing needs to be the same, so if I have two spaces on one side I need two spaces on the other. Granted having one space on each side of our assignment operator is common practice."Hello, playground"
– this is the value you are setting to our variable. Notice the""
quotation marks on either side of the words. This is so Swift knows when our non-code text starts and ends. We will talk more about the significance of these quotation marks later on in this lesson.
Now we covered what we started with, so let’s actually write our own first variable.
var myFirstVariable = "Hello, World!"
Awesome, we have officially started becoming programmers! So we have said variable 6 times now, what does that actually mean. When we really get down to it its talking about a piece of information we want to store temporarily. When we talk about variables specifically we are also saying that piece of information is subject to change. So If I make a new variable called name and give it the value of “Finn” I can change it later like this:
var name = "Finn" name = "Jake" name = "Simon"
Side note: when we are making new variables we can actually do so only using one var keyword if we put them all on the same line, like this:
var x = 0, y = 2, z = 1
I wouldn’t personally recommend doing it like this as it gets confusing, and makes your code less readable.