Swift: Alternative to Default Implementations in Protocols

I recently wrote about why I prefer not to use default implementations in Swift protocols.

TL;DR

  • I want a lot of conscious thought put in into each method of the protocol – adding a default implementation will make it easy to forget and not think about much. Oh, and the compiler won’t complain!
  • I want it to be easy to make changes in the implementation. If a method is not included in the file because the implementation is in the protocol, it’s more work to make the decision to add that into the file. The assumption is that the default should win. If it’s already there, it’s easier to just go in and make a small change.
  • Similar to the above point, I want it to be super readable where each method is coming from. If a bunch of methods are in the default implementation of the protocol, it’s not as clear just by looking at the file.

But there might still be repeating or “default” implementations that are shared across protocol implementations. In my case, I approached this issue by creating an object with some variables that could be shared across protocols:

However, when I wrote the article about it, @jckarter tweeted the following:

In my case, it didn’t make sense to create a separate protocol with default implementation because the use of the default values is pretty random – there isn’t any type of session that will use all defaults at the same time (this is one reason I didn’t want to include a default implementation in the first place).

But this did spark another idea! I could make my data defaults object conform to the same protocol as the objects where the defaults are being used – in my case, SessionDisplayable:

The best part about this is that when a method needs to use the default implementation, it can use the defaults method that has the same exact name as the method being implemented!

Here is an example of another SessionDisplayable using the new defaults:

I’m very happy with this solution. It’s super easy to use the defaults, but still allows for the compiler to complain when a protocol method is not implemented.

Enjoy the article? Join over 17,500+ Swift developers and enthusiasts who get my weekly updates.

  • Sam Duke

    Composing like this looks a little bit painful, especially if the protocol weren’t just vars but were functions requiring variables to be fwded. I left another comment on your other post about abstract classes in Java.

    To me it looks like the composition pattern you’re using here looks perfect for the problem, but I don’t think this is a replacement for default implementations on protocols in general