Class-only Protocols: class or AnyObject

Swift Protocol

The delegation pattern is widely used in the iOS system. If you are an experienced Swift developer, you know that the following code won't work with this pattern.

class MyClass {
weak var delegate: MyDelegate?
}

protocol MyDelegate {
}

You will get compiled error like this:

'weak' must not be applied to non-class-bound 'MyDelegate'; consider adding a protocol conformance that has a class bound

To make a protocol work with weak keyword, you have to limit a protocol adoption to class types.

protocol MyDelegate: class {

}

If you declare class-only protocol like the example above, I assume you have been writing in Swift for too long, maybe far too long. You might not realize that : class is no longer a recommended way of declaring class-only protocol.

From Swift 4, class keyword is deprecated. Even the compiler doesn't give out any warning at the moment.

This proposal merges the concepts of class and AnyObject, which now have the same meaning: they represent an existential for classes. To get rid of the duplication, we suggest only keeping AnyObject around. To reduce source-breakage to a minimum, class could be redefined as typealias class = AnyObject and give a deprecation warning on class for the first version of Swift this proposal is implemented in. Later, class could be removed in a subsequent version of Swift.
SE-0156 Class and Subtype existentials

You should declare it with AnyObject instead.

protocol MyDelegate: AnyObject {
}

What should I do? #

Replace all occurrences of class-only protocols from class to AnyObject and try to get used to a habit of using AnyObject from now on.

Why should I bother? #

Even class does not give out compiled error yet; I think it might in the future. And even though it won't, for better communication and understanding among your team, you should start using AnyObject. Because class is no longer present in official Swift documentation and a new generation of Swift developers might never know it exists.

Old habits die hard, but it has to die.

Reference #


Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy this article, you can subscribe to the weekly newsletter.

Every Friday, you’ll get a quick recap of all articles and tips posted on this site — entirely for free.

← Home