Reference Cycles with Closures
Sometimes assets appreciate or depreciate in value.
To demonstrate some closure-related memory management behavior, you will teach Asset
instances to react to changes in their value using a provided closure.
In your Asset
type, allow value
to be mutable and react to value changes by executing a stored closure of type (Asset) -> Void
.
Asset.swift
)class Asset { let name: Stringlet value: Doublevar value: Double { didSet { changeHandler(value - oldValue) } } weak var container: Vault? typealias ValueChangeHandler = (Double) -> Void var changeHandler: ValueChangeHandler = {_ in} init(name: String, value: Double) { self.name = name self.value = value } deinit { ...
Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.