Weak Delegate

Delegates should be weak to avoid reference cycles

  • Identifier: weak_delegate
  • Enabled by default: No
  • Supports autocorrection: No
  • Kind: lint
  • Analyzer rule: No
  • Minimum Swift compiler version: 5.0.0
  • Default configuration:
    KeyValue
    severity warning

Non Triggering Examples

class Foo {
  weak var delegate: SomeProtocol?
}
class Foo {
  weak var someDelegate: SomeDelegateProtocol?
}
class Foo {
  weak var delegateScroll: ScrollDelegate?
}
class Foo {
  var scrollHandler: ScrollDelegate?
}
func foo() {
  var delegate: SomeDelegate
}
class Foo {
  var delegateNotified: Bool?
}
protocol P {
 var delegate: AnyObject? { get set }
}
class Foo {
 protocol P {
 var delegate: AnyObject? { get set }
}
}
class Foo {
 var computedDelegate: ComputedDelegate {
 return bar() 
} 
}
class Foo {
    var computedDelegate: ComputedDelegate {
        get {
            return bar()
        }
   }
struct Foo {
 @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate 
}
struct Foo {
 @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate 
}
struct Foo {
 @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var extensionDelegate 
}
class Foo {
    func makeDelegate() -> SomeDelegate {
        let delegate = SomeDelegate()
        return delegate
    }
}

Triggering Examples

class Foo {
  var delegate: SomeProtocol?
}
class Foo {
  var scrollDelegate: ScrollDelegate?
}
class Foo {
    var delegate: SomeProtocol? {
        didSet {
            print("Updated delegate")
        }
   }