Difference Between Let And Var In Swift Explained

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts