What is the primary memory management issue in the following Swift code, and how can it be resolved?
iOS interview question for Intermediate practice.
Answer
A retain cycle occurs because Presenter strongly references CustomView, and CustomView strongly references Presenter via its delegate property.
Explanation
A strong reference cycle exists. The Presenter instance holds a strong reference to the CustomView via its customView property. The CustomView then holds a strong reference back to the Presenter via its delegate property. Because both references are strong, neither object can be deallocated, resulting in a memory leak. To resolve this, the delegate property should be marked as weak: weak var delegate: PresenterDelegate?.