visit
As the name suggests, variables are something that can vary.
To declare a variable, we use the var
keyword, followed by the name we want to give to that particular variable and assign it to something we want this particular variable to store in the memory.
var myNumber = 13
According to this code snippet, we declare a new variable called myNumber that stores the integer value of 13.
Now, myNumber, a variable has a value of 13 in the memory.
We can perform any kind of operations on this variable like mathematical calculations, building & solving logic, implementing algorithms, etc, just thinking of it as a substitute for the integer 13. And as we discussed above, we can change or manipulate this value.
myNumber = 26
No need to use the var
keyword again as we are trying to modify an existing variable that is already declared earlier.
Now the variable myNumber
has the value of integer 26 in the memory.
As you can see, after reassigning the variable to 26, the second print(myNumber)
statement prints out 26 in the console.
If we are reassigning the variable to a new value, the new value should be of the same data type of which the variable was earlier declared for:
var myAge = 18
myAge = 19
var myAge = 18
myAge = "eighteen"
As you can see, the Swift compiler shows us an error that it cannot assign a variable of type string to a variable that was earlier assigned an integral value.
var name = "John Doe"
print(name)
In this example, we store a variable of type string "John Doe" in the variable name and then we print it.
var isAdult = false
var isStudent = true
var myScore = 9.4
In this example, we store a floating value in the variable myScore
.
Good to know: We can explicitly declare a variable's data type to define what kind of data we want it to store in it.
var myAge:Int
myAge = 18
Here, we are explicitly telling the compiler to make sure that the variablemyAge
always stores an integer value only.
Also Published