Working with references

In Chapter 11, you saw the copy semantics involved when working with structures and other value types. Here’s a little reminder, using the DeliveryArea struct from that chapter:

When you assign the value of area1 into area2, area2 receives a copy of the area1 value. That way when area1.range receives a new value of 4, the number is only reflected in area1 while area2 still has the original value of 2.5.

Since a class is a reference type, when you assign to a variable of a class type, the system does not copy the instance; only a reference is copied. Contrast the

previous code with the following code:

let john = Person(firstName: "Johnny", lastName: "Appleseed") var homeOwner = john

john.firstName = "John" // John wants to use his short name! john.firstName // "John"

homeOwner.firstName // "John"

As you can see, john and homeOwner truly have the same value!

This implied sharing among class instances results in a new way of thinking when passing things around. For instance, if the john object changes, then anything holding a reference to john will automatically see the update. If you were using a structure, you would have to update each copy individually, or it would still have the old value of “Johnny”.

results matching ""

    No results matching ""