Swift

let and var: Constantly Updating

In Swift, we store data values in constants and variables that are identified by the let keyword, for constants, and the var keyword, for variables. 

When you declare a variable with a let, you are required to provide a value at creation. A var does not require to have a value upon creation but if it is provided, it can be updated later without failure.

Constant objects

Let’s say we create instances of a struct and class, making them constant:

In the above example, we set up an instance of a House struct and a Apartment class, both of which are constants signified by let. In step 3 you’ll notice the error Xcode throws an error when attempting to update the bedrooms value of house but not the bathrooms value of apt, even though they’re both constants. WTH?!?!

Going back to our discussion on class and structs, we recall that structs are value based type, meaning they retain copies of values, while classes are reference types, defined as enabled to retain a reference to same existing instance used. Essentially, since values of structs are copies, once the instance of a struct is created and set as a constant, it can no longer be updated since it has no reference to its location in memory. It only exists in the current lifecycle of the code.

An instance of a class that is marked as a constant is updatable because, since classes are reference types, the compiler is able to “reference” the address in memory and update it with new values. Now, if a property in the class is a constant, that will not be able to be updatable.

In the above image, you’ll notice we updated the bathrooms property of the Apartments class to be constant. When we attempted to update the value from 1 to 2, Xcode shows an error “Cannot assign to property. bathrooms is a let constant”. Compared to the previous example, while apt remains a constant, attempting to update its bathrooms value is not allowed because it is now a constant. 

When to Use

Swift generally suggest to use constants when you can because since the values cannot change, it makes them safer to user. This is because once the value is set for a constant, you have the guarantee that value will remain unchanged through the lifecycle of the operation it is being used in. However, you’re more likely to use vars to allow for updates to the object, enabling changing the state of the object when used in structs and classes.

Conclusion

Variables make up the objects that retain values in Swift. They can be immutable and mutable by applying a let or var keyword, respectively. When you need a value to not be able to changed, apply a let to a variable to make it constant. If you need to be able to update a variable, use the var keyword.