Weak Delegate References

ID

swift.weak_delegate_references

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Swift

Tags

memory-leak, reliability, suspicious-code

Description

Reports a stored var delegate (or any var *Delegate) property inside a type declaration that lacks a weak (or unowned) modifier. The Cocoa / UIKit delegation pattern points an object at a peer that, in turn, points back at the owner. When the owner holds the delegate strongly, neither side can ever be released and both leak.

class V {
    var delegate: MyDelegate?              // FLAW — strong reference
}

class V {
    weak var delegate: MyDelegate?         // OK
}

Rationale

ARC reclaims an object only when its strong reference count drops to zero. A strong delegate participates in a reference cycle that ARC cannot break, so the owner, the delegate, and every object they transitively reach stay alive for the lifetime of the process.

The rule fires only for stored var properties whose name is delegate or ends in Delegate, declared inside a type. Computed properties and static type-level vars do not own a reference in the same way and are ignored.

Remediation

Declare the property weak (the usual choice for a class-bound protocol) or unowned when the delegate is guaranteed to outlive the owner:

weak var delegate: MyDelegate?
unowned var owner: Container