Here’s my current solution. I wasn’t sure how to set/update totalValue variable as a computed property, so I set its value in the store(_ asset:) method which was the only way I could access the new values.
Is there a way to include the original values of each asset? For example, if the Rare Coin asset has an initial value of 1_000.0, and I updated it by 137, then the output should say "New total value: optional(1137.0).
class Vault {
let number: Int
private(set) var assets = [Asset]()
var totalValue: Double = 0
init(number: Int) {
self.number = number
}
deinit {
print("\(self) is being deallocated")
}
func store(_ asset: Asset) {
asset.container = self
asset.changeHandler = { [weak self] (change) in
self?.totalValue += change
print("An asset has changed value by \(change). New total value: \(String(describing: self?.totalValue))")
}
assets.append(asset)
}
}
extension Vault: CustomStringConvertible {
var description: String {
return "Vault(\(number))"
}
}
class Simulation {
func run() {
let vault13 = Vault(number: 13)
print("Created \(vault13)")
let coin: Asset = Asset(name: "Rare Coin", value: 1_000.0)
let gem: Asset = Asset(name: "Big Diamond", value: 5_000.0)
let poem: Asset = Asset(name: "Magnum Opus", value: 0.0)
vault13.store(coin)
vault13.store(gem)
print("Created some assets: \([coin, gem, poem])")
coin.value += 137 // New total value: Optional(137.0)
gem.value += 50 // New total value: Optional(187.0)
}
}