Understanding mutability and immutability
Swift doesn't require that you define separate mutable and immutable types. When you create an array, set, or dictionary variable using the var
keyword, it will be created as a mutable object. You can modify it by adding, removing, or changing the value of items in the collection. If you create an array, set, or dictionary using the let
keyword, you are creating a constant object. A constant collection type cannot be modified, either by adding or removing items, or by changing the value of items in the collection.
Mutability of collections
When working with collection types, you need to understand how Swift treats mutability between structs and classes. Some developers tend to get confused when working with constant class instances because their properties can still be modified.
When you create an instance of a structure and assign it to a constant, you cannot modify properties of that instance, even if they are declared as variables. This is...