Alexito's World

A world of coding 💻, by Alejandro Martinez

🔗 Linked post

Check out the linked article.

Swift alternatives to protected

Yesterday I made a question about the acces controls that we have in Swift: Why internal and no protected?

There was not a really good answer in the social networks and I asked the same question in a Meetup without a really good answer neither. One of the answers was not to use subclasses, and even I'm not a big fan of class hierarchies, this is not a good answer for me. In occasions subclassing is the best pattern for solving some typical problems.

Thankfuly Jared Sinclair has written an amazing blog post talking about the alternatives to the protected access control for Objective-C and Swift.

In the post Jared talks about how Apple made public some methods thanks to him (curious anecdote, must read) and how Apple uses a semi-protected pattern in Cocoa: The “Protected Extension” Design Pattern.

According to this design pattern, the parent class [...] depends upon a handful of extension methods overridden by its subclasses. Other classes that are simply using a gesture recognizer should never call these methods since that could trigger unwanted effects. But the methods still need to be exposed in a semi-public fashion to allow subclasses to provide their override implementations.

For me this is a really interesting pattern semi hidden in Cocoa, but the bad thing is the should word. There is nothing in the language that prevents you from calling those methods, just convention. It's good because we have a semi-protected pattern, but it's never good enough having a semi thing.

Jared continues talking about alternatives to the pattern in Swift. For now the only good way fo doing it is using the private key and putting the subclasses in the same file, wich is far from perfect. Outside classes can't overwrite your protected methods. We can't use the same pattern that we have in Objective-C because declarations from extensions cannot be overridden yet.

I hope that Apple give us more nicer ways of doing this in the near future. Read more on Jared post: For Subclass Eyes Only: Swift, UIGestureRecognizer, and the Protected Extension Pattern

If you liked this article please consider supporting me