Swift extensions can be applied to Objective-C types

The more I think about this, the more obvious it sounds. And the more I think about it, the less I believe it deserves a post. But it was a pleasant surprise anyway, so here it goes.

Let’s assume we have an Objective-C project, that contains a class like this:

And it also contains another class like this:

Now, let’s say we declare a Swift protocol like this:

And extensions to the Person and Movie object to enforce compliance with the Displayable protocol:

Now, we can consume the Displayable protocol from Swift:

Or from Objective-C (please, excuse the weakness of my ObjC-generics kung fu):

Which, believe me, is a huge relief when dealing with large legacy projects.

In case you want to play with a complete example, I uploaded a sample project to GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *