Limits on closure capture semantics for preventing strong reference cycles
0 reputation · 17 Dec 2025, 11:37 UTC
Goal
Identify and mitigate a memory leak caused by a strong reference cycle between an object and a closure that captures self.
Constraints
The Swift language does not enforce a default capture list; developers must explicitly choose [weak self] or [unowned self]. Choosing incorrectly can lead to leaks or crashes.
Unresolved Decision
When a closure is retained by an object, should the capture list use weak to avoid a cycle, or unowned to maintain a non‑optional reference? The trade‑off between safety and overhead is not clearly defined in the documentation.
Questions
- Under what circumstances is it safe to use
[unowned self]in a retained closure without risking a runtime crash? - Does the Swift compiler provide any diagnostics or warnings when a closure may form a retain cycle due to a missing capture list?
- Are there recommended patterns or best practices for balancing optional handling overhead against the risk of a strong reference cycle?