Reference Cycles in Closures

Time to add an accountant class that will keep track of a Person’s net worth. Create a new Swift file called Accountant.swift and define your new class.

Listing 24.9  Defining an Accountant (Accountant.swift)

import Foundation

class Accountant {
    typealias NetWorthChanged = (Double) -> ()

    var netWorthChangedHandler: NetWorthChanged? = nil
    var netWorth: Double = 0.0 {
        didSet {
            netWorthChangedHandler?(netWorth)
        }
    }

    func gainedNewAsset(asset: Asset) {
        netWorth += asset.value
    }
}

Accountant defines a typealias, NetWorthChanged, which is a closure that takes a Double (the new net worth value) and returns nothing. It has two properties: netWorthChangedHandler, which is an optional closure to call when ...

Get Swift Programming: The Big Nerd Ranch Guide 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.