Class Delegate Protocol

Delegate protocols should be class-only so they can be weakly referenced

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

Rationale

Delegate protocols are usually weak to avoid retain cycles, or bad references to deallocated delegates.

The weak operator is only supported for classes, and so this rule enforces that protocols ending in “Delegate” are class based.

For example

protocol FooDelegate: class {}

versus

protocol FooDelegate {}

Non Triggering Examples

protocol FooDelegate: class {}
protocol FooDelegate: class, BarDelegate {}
protocol Foo {}
class FooDelegate {}
@objc protocol FooDelegate {}
@objc(MyFooDelegate)
 protocol FooDelegate {}
protocol FooDelegate: BarDelegate {}
protocol FooDelegate: AnyObject {}
protocol FooDelegate: AnyObject & Foo {}
protocol FooDelegate: Foo, AnyObject & Foo {}
protocol FooDelegate: Foo & AnyObject & Bar {}
protocol FooDelegate: NSObjectProtocol {}
protocol FooDelegate where Self: BarDelegate {}
protocol FooDelegate where Self: BarDelegate & Bar {}
protocol FooDelegate where Self: Foo & BarDelegate & Bar {}
protocol FooDelegate where Self: AnyObject {}
protocol FooDelegate where Self: NSObjectProtocol {}

Triggering Examples

protocol FooDelegate {}
protocol FooDelegate: Bar {}
protocol FooDelegate: Foo & Bar {}
protocol FooDelegate where Self: StringProtocol {}
protocol FooDelegate where Self: A & B {}