PROGRAMMING

Stop Using Protocols!

Use value types instead.

Riccardo Cipolleschi
6 min readAug 25, 2020

--

During 2015 WWDC, Apple held a session on Swift programming promoting the famous paradigm:

“Always start with a protocol!”

Four years later, in 2019, Apple stated that it’s not a good idea to always start with a protocol. They suggest starting with concrete types in another session and, eventually, abstract them in a protocol later.

Recently, I was watching the content of pointfree.co: a video series of Swift programming with a functional approach. In one of their collections, they presented a concept that is really illuminating: Protocol Witnesses. This is practically what the compiler does under the hood and they can simplify a lot our code.

Today I’d like to explore this concept a little bit more, focusing on the most prominent protocols’ use cases.

Use Cases

Protocols are a great feature and they are at the foundation of Swift. They permeate all the standard library and Apple pushes us to use them in our code to increase the separation of concerns.

We mainly use protocols for two reasons:

  1. To model interfaces and requirements.
  2. To abstract common behaviors and improve generalization.

Interface Modeling

Protocols are really useful when we have to describe a requirement of our app that is provided by another framework or module.

Let’s imagine that the app needs to interact with a Service to download a list of products and the details of a single product. The app doesn’t implement the client-code that interacts with the service, but it needs those APIs. Also, we want to test our code, so we need to mock that dependency easily.

To satisfy all these assumptions, we write the following protocol:

--

--

Riccardo Cipolleschi

Hey there, I’m Riccardo. Software engineer at Meta. I have a passion for iOS and I love to share my knowledge with others.