Create a Variable
var variableName = value
let variableName = value
var handHeldFood = "Pizza" // this is a string var numberOfServings = 1.2 // this is a double var numberOfForks = 1 // this is an integer let bestHeldFood = "Nugget" // this is a constant string
Note : A “var” can be changed later where as a “let” can’t.
Think of it as “let” is like write a variable with a pen. What you write can’t be changed.
“var” variables on the other hand are like writing in pencil. You can use the same paper to write and erase values over and over.
If you code “let it rain!” there is no bringing out the sun again!
! No mathematical symbols in the variable name.
! Don’t start a variable name with a number.
The variable type is determined or “inferred” by the value. You can be explicit but you don’t have to be and the remainder of this guide will leverage Swift’s inferred type systems.
Swift will always infer a type of Double over Float.
Edit a Variable
variableName = value
var handHeldFood = "Pizza" // This sets the variable handHeldFood = "toast" // this changes the variable
Copy a Variable
var variableName = otherVariableName
var handHeldFood = "Pizza" // This is “Pizza” var triangleFood = handHeldFood // Now this is “Pizza” too triangleFood = "nacho chip" // Change to “nacho chip” triangleFood // this is “nacho chip” handHeldFood // this is still “Pizza”
Note : Why is this important?
Copying variables used to just simply copy a reference to the same value. That means two different names for the same value. The problem is that when you change the value of one, it changed it for the original. In swift, every different variable is independent. So copying a variable into another variable is just that.. a copy of the original.