2

I have recently inherited a quite undocumented, spaghetti-esque and extremely buggy project written in Swift.

Am tidying up some things here and there, and came across this on every single protocol declaration:

protocol SomeProtocol: class { ...

as in literally : class - that is not a placeholder for something else.

My question is: What does the : class achieve or declare?

Personally have never put the : class afterwards, I usually reserve that for inheriting from other protocols. I removed a couple without result, but figured I should check the actual purpose (if any) before I continue.

Best regards,

Frankie

1 Answers1

1

: class means that this protocol can only be conformed to by a class.

One use case of this is delegates. delegate properties are usually declared as weak to avoid retain cycles. For example:

class MyCoolClass {
    weak var delegate: MyCoolClassDelegate?
}

If MyCoolClassDelegate is declared like this:

protocol MyCoolClassDelegate { }

Then structs can conform to it as well. But struct types can't be declared weak! Therefore, this error occurs:

'weak' may only be applied to class and class-bound protocol types, not 'MyCoolClassDelegate'

This is why you need to declare it as : class.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Nitpicking: *"... by a reference type, namely, a class."* – Reference type and class are not synonyms, a closure is a reference type as well. A class protocol can only be adopted by a class. – Martin R Dec 02 '17 at 09:44