Difference Between Let And Var In Swift Explained

let and var are some of the most common keywords used in Swift

Difference Between Let And Var

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.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts