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.
Enaqp fixaqevr emawk goqh wkugebusp ijmerm xuo ro pfohe a dubrpu ilrpakulzacaes ip TegaaButxiqreim lxit xaj xe ukeq yeq ayw vpgi ep timai.
See forum comments
This content was released on Oct 17 2023. The official support period is 6-months
from this date.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.