let or var in Swift, and why it absolutely matters

The compiler may complain all the time if you get it wrong!

When using Swift, you are allowed to create both variables and constants. The two are different things, but what are they and why does Swift think it so important to make the distinction?

Image for post
Image for post
Photo by Oladimeji Odunsi on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” Swift application (guide HERE)

OR

  • Be able to use Swift Playgrounds (guide HERE)

Terminology

compiler: A program that converts instructions into a machine-code or lower-level form so that they can be read and executed by a computer.

constant: A value that can not be amended during the normal execution of a program

variable: A variable that can be amended during the normal execution of a program

Making a variable

We can have a constant anywhere in our code

var width = 5

width = 6

So after the second command, width will store the value of 6. Great!

Making a constant

We can have a constant anywhere in our code

let height = 5

This constant cannot be changed afterwards. If we try to, like making the height 6 like:

height = 6

will produce a rather upsetting message from the Swift compiler.

Image for post
Image for post

Which is not a great. Yet this is what Swift declares when you try to change a constant. Read on:

What is going on?

Constants are much more of a known quantity. You write down the value once, and then it stays.

In fact, if you write a value and make it a var but don’t change the value, the Swift compiler will suggest your switch it to a let . This means that Swift itself favours constants.

But this is not just the write once rule, but opens up a world of compiler optimisations that can make your apps run faster without you doing any more work!

Conclusion…

It can be annoying that the compiler gives you warnings about making your variables a let or a var. However, once we understand that the compiler is actually helping us make better software this becomes an easier pill to swallow.

Happy coding!

Want to get in contact? Try the link here:

https://twitter.com/stevenpcurtis

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store