Swift Needs Protected Access Level
Carlos Ribas

I agree. Apple’s explanation of why there is no protected accessor and generic interfaces just shows they themselves are either lazy or do not understand OOP and SOLID principles. Below is my example that has become a pain.

We use Reactive Programming here with a Clean Architecture approach. This means I’m using Views and Presenters and something I call a Binder that hooks up observables/bindings to the controls in an Controller with a corresponding field in a Presenter. Reactive Programming returns me a Disposable that I can add into a DisposableBag. So naturally, if all binders need to add disposables to a disposable bag, this leads into inheritance with a Binder base/super class and subclasses.

DisposableBag is a smart bag. If I instantiate a new bag, it ensures all disposables in the bag are disposed for me. So I would like to have a protected abstract bind method that is overridden by subclasses to hookup the bindings between the view and presenter. But I would also like a public method in the Binder super class to start the bindings to ensure the DisposableBag is reinstantiated each time bind is called. This method would then call the abstract method. I cannot do this with Swift. Why? I can’t prevent an idiot from calling the bind method like I want. So now my subclasses have to be smart enough to ensure the bag is reinstantiated.

This is freshman college level OOP concepts that Apple ignores and frankly it is disturbing. Yes, inheritance can become tricky and people use it incorrectly. However, inheritance and hierarchy is an import principle in OOP. It’s what allows us to extend behavior if we want to support reuse or work with 3rd party libraries or frameworks. Sure, iOS Swift supports extension methods, but extension methods are not a replacement for inheritance.

Apple is not only violating OOP principles, they are also ignoring the SOLID principles of coding. By not allowing for proper inheritance it is a direct violation of the Liskov Substitution principle. For those of us who follow SOLID principles, we see less technical debt and a more readable code base that is easier to add features to and maintain. However, Apple’s dumb decisions like these, prevent good coding practices. I wish I could share the differences between our Android projects and our iOS Swift projects. Less code, cleaner, and more readable code definitely lives in Android. Why? Proper inheritance is supported as well as generic interfaces.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.