iOS, Objective-C, Swift, Design and Whatever Comes in Mind
‹ Back to the Blog

Swift 4 Change: Limit a Protocol Adaption to Reference-Type-Objects

Often I need to declare a protocol and need a weak reference to it. It is quite common in the delegation pattern.

In order to store a weak reference, the implementing type needs to be a reference type. Therefore, the protocol must limit the type of its implementation so that only classes can implement it.

Swift 4 now introduced a new, preferred way to declare a class-only protocol: ​AnyObject​.

However, the old way, where you have to use the ​class​ keyword still works fine. Prior to Swift 4, there were some subtle differences between these two keywords, which has been removed in SE-0156 - Class and Subytpe existentials.

So now you can declare a protocol like this:

Only objects can implement it, so the compiler will prevent the following code form beeing compiled:

In addition to that, the protocol can still be used by a weak reference, like

The old way, the ​class​ keyword is not yet deprecated, but you can start accustom yourself to using ​AnyObject​ now.

The information in this article are taken from here.

"Swift 4 Change: Limit a Protocol Adaption to Reference-Type-Objects".