O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) -> Void

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

    func gained(_ 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 the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required