Instruction 2

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

Protocol Extensions

You’ve now seen how to build and use relatively complex protocols. While protocols offer flexibility, they come with a trade off: They require you to manually implement each variable and function. Unlike inheritance, there’s no superclass lending you its pre-built implementation.

In the media collection example, this would mean that every MediaCollection implementation would need a getDescription() function. This is likely to be almost the same for every collection type — you’re going to print the number of items in that collection.

Implementing this for every collection type is a lot of duplicated code that you would need to update if the protocol ever changes. Fortunately, there is a better way!

Swift allows you to extend protocols to provide additional computed properties and function implementations. This is extremely handy for providing useful functions for all implementations of a protocol. It also allows you to provide a default implementation for a required function, so the implementer doesn’t need to implement it themselves. This cuts down on duplicated code and also allows you to add functions to protocols without breaking existing code (because the existing implementations will use the default implementation).

The compiler uses the default implementation unless the type implements the function itself — in which case, the compiler uses that implementation instead. This allows you to have default implementations and override it in your types if needed, much like with inheritance.

Generics and Protocols

Protocols also integrate nicely with generics in Swift. With protocol extensions, you can remove the duplicated code for getDescription(). However, there’s even more room for improvement. Each type of media collection is going to be pretty similar, with the only real difference being the associated type.

See forum comments
Download course materials from Github
Previous: Demo 1 Next: Demo 2