Mutability and constants

The previous example may have had you wondering how you were able to modify jane even though it was defined as a constant. You may also wonder why you are able to mutate the instance of Student without providing the mutating keyword that is required for methods in structs that modify values.

When you define a constant, the value of the constant cannot be changed. If you recall back to the discussion of value types vs reference types, it is important to remember that with reference types the value is the reference itself.

The value of “pointer1” in red is the immutable value of jane. If you were to attempt to assign another student to jane, you would get a build error:

// Error: jane is a let constant

jane = Student(firstName: "John", lastName: "Appleseed")

If, instead, you created jane as a variable, you would be able to assign to it another instance of Student on the heap:

var jane = Student(firstName: "Jane", lastName: "Appleseed") jane = Student(firstName: "John", lastName: "Appleseed")

After the assignment of another Student to jane, the pointer value behind jane

would be updated to point to the new Student object.

Since nothing would be referencing the original “Jane” object, its memory would be freed to use elsewhere — a topic you’ll cover in detail in Chapter 23. :]

Any individual member of a class can be protected from modification through the use of constants, but because reference types are not themselves treated as values, they are not protected as a whole from mutation.

results matching ""

    No results matching ""