Swift

Swift

Made by DeepSource

Delegates should be weak to avoid reference cycles SW-W1025

Bug risk
Major

Delegates in Swift should be declared as weak to avoid creating reference cycles. When a delegate is strongly referenced by the object it is delegating to, a retain cycle can occur preventing both objects from being deallocated and causing a memory leak.

Delegates should almost always be weak references. This is because if the delegator is deallocated from memory, the delegate is no longer needed. If the delegator is nil and the delegate tries to perform an action on it, this will result in a nil exception and crash the application.

Strong delegate references are one of the leading causes of memory leaks and developers should be very careful before creating a strong delegate reference.

Bad Practice

class Foo {
  var delegate: SomeProtocol?
}

Recommended

class Foo {
  weak var delegate: SomeProtocol?
}