Review generated dashboard binding

from Automatic reference counting
Swift 6.3.3 advanced 6 min 3 issues to find

Review this generated dashboard binding for lifetime safety and repeatable rebinding.

Bind a controller to a data source. Refreshing must stop safely when either object is released, rebinding must detach the old source, and the relationship must not form a cycle.

swift
final class DataSource {
    var onChange: (() -> Void)?
    func load() -> [String] { ["open", "closed"] }
}

final class DashboardController {
    var rows: [String] = []
    var refreshHandler: (() -> Void)?

    func bind(to source: DataSource) {
        refreshHandler = { [unowned self] in
            self.rows = source.load()
            print("rows", self.rows.count)
        }
        source.onChange = self.refresh
    }

    func refresh() {
        refreshHandler?()
    }
}

generated code is illustrative, not from any one model

Open in playground
Report an error