Did set

I tried this code in the playground and it doesn't work. What is interesting - the fixed version. I was not expected this.

class SomeController: PresenterListener {
    var presenter: Presenter? {
        didSet { presenterUpdated() }
    }
    private func presenterUpdated() {
        presenter?.listener = self
    }
}
protocol PresenterListener: class {
}
protocol Presenter {
    var listener: PresenterListener? { get set }
}
class SomePresenter: Presenter {
    weak var listener: PresenterListener?
}
let controller = SomeController()
controller.presenter = SomePresenter()
print("✅")

Your code has infinite recursion. The line “presenter?.listener = self” causes a mutation of self.presenter, which is modeled as first getting the value then setting it. That means it triggers the didSet handler, which starts the same loop over again endlessly.

1 Like

Yep, that is recursion. Isn't it looks strange when the working code looks like this?

class SomeController: PresenterListener {
    var presenter: Presenter? {
        didSet {
            presenter?.listener = self
            presenterUpdated()
        }
    }
    
    private func presenterUpdated() {
        //...
    }
}
Terms of Service

Privacy Policy

Cookie Policy