Advanced Swift: Values and References, Episode 7: Challenge: COW | Kodeco, the new

In this challenge you will try to implement a copy-on-write that reduces reference counting traffic.

This is a companion discussion topic for the original entry at

Hi Ray and team,

Why do we make the copy inside of the getter rather than the setter? Wouldn’t that make a copy on read rather than on write?

Thank you!

Sorry, I get it now. We only use _mustatingStorage computed property inside of the setters. I guess the alternative would be something like this:

struct InventoryItem {
  private var storage: Storage

  private final class Storage {

  init(name: String, cost: String, barcode: String, color: UIColor, images: [UIImage], comment: String) { = Storage(name: name, cost: cost, barcode: barcode, color: color, images: images, comment: comment)

  var name: String {
    get { }
    set {
      if !isKnownUniquelyReferenced(&storage) {
        storage = Storage(name: newValue, cost: storage.cost, barcode: storage.barcode, color: storage.color, images: storage.images, comment: storage.comment)
      } = newValue

// ...

Then we only need a single private property, but it requires a lot more code as the isKnownUniquelyReferenced logic needs to be repeated for each property.

1 Like