let and var are some of the most common keywords used in Swift
The let
keyword in Swift defines a constant.
let favoriteFood = "eggs"
Constants cannot be changed. You cannot change the value of favoriteFood
above once you have set it.
If you try to change a constant you will get an error. Try this:
let favoriteFood = "eggs"
favoriteFood = "fries"
You will get an error that says Cannot assign to value: 'favoriteFood' is a 'let' constant
.
The var
keyword in Swift defines variables.
var dinner = "pizza"
Variables can be changed.
var dinner = "pizza"
dinner = "rice"
If you know the value of something won’t change, I recommend you set it as a constant. This prevents you or your teammate from changing the value by accident. Constants also allow the compiler to perform some optimizations to your code as well.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.