Swift: Protocol Composition 😍

I’ve been incorporating Protocol-Oriented Programming more and more in my Swift code and I LOVE it!!! Thanks again to @mhollemans for the article on Mixins and Traits in Swift 2.0 – that really helped me understand how to use protocols in a very powerful and beautiful way.

However, I’ve found that in practice, my objects sometimes conform to too many protocols, so the method or classes that take in these protocols become way too long and a bit confusing, just like in the below configure method:

So one solution to this that I really like was suggested to me by @zachwaugh: Protocol Composition!!! It looks like this:

I seriously love this 🤓😍. It is readable, avoids generics, and communicates the intention of the protocols very clearly. Thanks again @zachwaugh for suggesting it!

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

  • Mustafa Yusuf

    I don’t event know this protocol thing. That’s great. One final thought on func configure(presenter: SwitchWithTextViewPresentable). I think it should be generic. Like this func configure(presenter: T). The differences between protocol version and generic version is first one uses dynamic dispatch and the second one uses static dispatch. Here is further explanation: http://airspeedvelocity.net/2015/03/26/protocols-and-generics-2/

  • This article really helped me wrap my head around Protocol-Oriented Programming (which has been an ongoing process). Thank you.

  • Kamil Pyć

    This is even possible in Objective-C 😉

  • zjczhjuncai

    I love this approach

  • Xavi Matos

    typealias FTW

  • Dominic Frei

    Awesome! I am using type aliases here and there. But this is by far the best example I have seen to far. Even though Mustafa’s post shows that you should always think about which way to go!

  • Wenbin Zhang

    Yup, definitely shows the beauty of Swift.

  • oh god, how did you know this…

  • It’s worth noting that in Swift 3 the protocol syntax has been replaced and the typealias would now be:

    typealias SwitchWithTextViewPresentable = TextPresentable & SwitchPresentable & ImagePresentable

  • David Rynn

    Looks like the Swift 3 syntax has changed to
    typealias SwitchWithTextViewPresentable = TextPresentable & SwitchPresentable & ImagePresentable

  • M@t

    Hi,

    in your presentation https://academy.realm.io/posts/doios-natasha-murashev-protocol-oriented-mvvm/
    you have a signature:

    class SwitchWithTextTableViewCell: UITableViewCell

    In this post you use Generics in the function (instead of class):
    func configure(presenter: T) {

    Why different approach?

    also, the first solution gives me a prob when registering a cell using @gonzalezreal pattern. SwitchWithTextTableViewCell.self is no longer possible and not sure what´s the workaround.

    please enlighten me….

    keep up the good work!