Frank Jones
Frank Jones

Reputation: 23

Trying to understand something with Swift protocols

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

Upvotes: 2

Views: 59

Answers (1)

Sweeper
Sweeper

Reputation: 271185

: 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.

Upvotes: 1

Related Questions