Protocols are great! I use protocols. You use protocols. We all use protocols! They allows us to code to an interface rather than an implementation, and we’ve heard many times that this is a powerful idea. It gives you the ability to completely swap out implementations if you wanted, which is what many people do with their dependencies. They use live versions in production, but then substitute mock versions while testing.
However, protocols can’t possibly be the be-all and end-all of code reuse and extensibility in our Swift code. For one thing, they have a lot of problems that have to be dealt with! I’m sure everyone has come across the dreaded “Self or associated type requirements” error, and that’s always annoying. Also, protocols are quite rigid in that a type can conform to a given protocol in only one single way. Sometimes it’s completely valid and even technically correct to allow a type to conform to a protocol in multiple ways.
It turns out that basically every Swift protocol can be directly translated to a struct representation, and we’ve even done this process in a previous episode but we just didn’t dissect it. Doing this translation fixes a lot of the problems with protocols, but also introduces a few new quirks. Even cooler, this translation process is completely algorithmic. We can describe a set of steps that allows you to sit down and translate any protocol into a struct via a step-by-step process.