One of the first things a coder notices about Swift is var and let. It seems like an odd system at first and when you add in optionals it can seem downright bizarre.
let nilableBool:Bool?
Wha???
Let's start again.
What is var?
Var is exactly what you would expect it is. It's what you use when you declare something as a variable. That means you can modify it however you like!
var num = 0
num += 3 // Ok!
num = 0 // Ok!
num = nil // Nope!
Ok, not quite any way you like!
What is var??
This is a new question! Var? is a different kind of variable. It says it is a variable that can have any value that the type allows, or, nil. This is called an optional.
var num:Int?
num = 0
num! += 3 // Ok!
num = 0 // Ok!
num = nil // Ok!
What is let?
Let is Swift's way of declaring a constant. It means you won't be able to modify it after you set the value.
let num = 0
num += 3 // Nope!
num = 0 // Nope!
num = nil // Nope!
Wait... There's a let? how does that work?
Optional let is surprisingly useful. Especially since it seems so useless at first glance
let theValue:Bool?
if something {
theValue = true
}
else if somethingelse {
theValue = false
}
else {
theValue = nil
}
Look! Now you have the world's best return value! (Seriously, half the functions that return Bool would be better off if they returned Bool?)
Optional var or everybody!
Please don't do that! If you have a variable that is changed then use var. Otherwise use let. Using let will keep you away from a large set of bugs involving modifying things that shouldn't be modified.