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 https://www.kodeco.com/1940309-advanced-swift-values-and-references/lessons/7
In this challenge you will try to implement a copy-on-write that reduces reference counting traffic.
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) {
self.storage = Storage(name: name, cost: cost, barcode: barcode, color: color, images: images, comment: comment)
}
var name: String {
get { storage.name }
set {
if !isKnownUniquelyReferenced(&storage) {
storage = Storage(name: newValue, cost: storage.cost, barcode: storage.barcode, color: storage.color, images: storage.images, comment: storage.comment)
return
}
storage.name = 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.