I know I know I know before you say anything I understand this statement is probably ridiculous. However, this topic could aid someone or more likely open the floor to discuss concepts in general so without hesitation, we will dive into it.
let and var so what are they and their differences
As you probably already know both let and var are for creating variables within Swift. Now with let it helps create an immutable variable(s) so consider it a constant but var is used for creating a mutable variable(s). Nonetheless, a variable created by either of them holds a reference or a value.
The difference between the two is that when a developer creates a constant with let the value must be assigned before you can use it. While when you declare a variable with var it can be used before or after an assignment or never use it as well as reassigning it on the fly.
Mutate function parms
function parameters are constants by default. Trying to change their value within the function body results in a compile-time error.
func pokedex(for name: String) { name = "charmander" } pokedex(for: "mex") //Line 2 cannot assign to value is let constant
Test: Build & Compile
struct Pokemon { var name: String let weakness: String } let trainerAPokemon = Pokemon(name: "Charmander", weakness: "water") trainerAPokemon .name = "Bulbasaur" trainerAPokemon .weakness = "fire" var trainerBPokemon = Pokemon(name: "Pikachu", weakness: "rock") trainerBPokemon.name = "Squirtle" trainerBPokemon.weakness = "electricity"
In the example above we are using a struct. Whenever you try to muate them they get copied with mutation applied to them and reassigned back.
Now let’s review everything within the block. The let variable within the struct cant is mutated as it would mean you are mutating the value of an immutable variable. However, our friend the var variable within the struct can be mutated.
- Line 7
- cannot assign to the property trainerAPokemon because it is a let constant
- Line 8 & 12
- cannot assign to the property weakness because it is a let constant
Test: Build & Compile
class Pokedex { var name: Int let num: String init(name: String, num: Int) { self.name = name self.num = num } } let trainerA = Pokedex(name: "Lucario", num: 448) trainerA.name = "Squirtle" trainerA.num = 7 var trainerB = Pokedex(name: "Bulbasaur", num: 1) trainerB.name = "Gengar" trainerB.num = 94
In the example above we are now using a classes. When attempting to mutate them, the object stored elsewhere in memory gets mutated while the reference to it remains the same.
You can modify a class’s members whether or not the variable referencing it is mutable
- Line 13 & 17
- cannot assign to property num because it is a let constant