Advanced Swift 3 - Part 6: Implementing Copy-on-Write | Ray Wenderlich

Swift collections have value semantics and good performance because they are implemented with copy-on-write. This video shows how to do this for your own types.

This is a companion discussion topic for the original entry at

Hey Ray,

When we implement Copy-on-Write for the Monster with isKnownUniquelyReferenced(&reference) , we created the troll, initialized a monsters array with that troll, and then modified the troll’s hitPoints.

At the point when we modified the troll’s hitPoints, even just one time, we see making copy and no copy simultaneously. Why does the _mutatingMonster getter execute twice if we’re only accessing it once by modifying the hitPoints? I expected that modifying a property on the monster would have only resulted in one print statement per modification.

Great question. Sorry for the delay in responding. We updated the get request so the compiler is doing a read operation to get the current value and then a write operation to add 100. So there are two accesses to the variable.

When you have a mutating property it passes self as inout. One access is for the in and one is for the out. Because we are putting prints in the accessor the compiler can’t optimize this away. If we got rid of the prints and compiled in release, I would guess that it might optimize the accesses (though I haven’t tried this).

Hi Ray,

I have a question about the solution code to the challenge. It contains code like this:

var name: String {
    get {
    set {
        return = newValue

Should the return statement really be in the set clause? If so, what purpose does it serve?

@rayfix Do you have any feedback regarding all of this? Thank you - much appreciated! :]