One of the things I like most about Swift is that almost every day I learn something new, more often than not, something new that makes me write more readable and cleaner code.

Today I realised that protocol composition, which I kind of knew could be used to compose a SuperClass and a Protocol, can help remove some downcasts at runtime, and substitute those downcasts by the compiler yelling at you when writing the code.

Let’s take this code. As usual, it is difficult for me to come up with a relevant example that illustrates what I want, but is also simple enough to be understood without too much context.

Notice how I have to check, at runtime, that the parameter I pass to deliverPresentation implements the Presentable protocol.

If we rewrite the Presenter to be like this, we can make the compiler enforce that whatever we pass to deliverPresentation as a parameter also implements Presentable, so we can avoid the downcast.

A real life example? From this:

To this:

 

Leave a Reply

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