This is largely a type hierarchy. Suppose you have an object representing a GlowingRedCube , but you want this type to be used in a variety of common codes that concern:
- Various Shapes -
Cube extends Shape - Various colors -
Red extends Colorful - Different types of lighting -
Glowing extends Illuminated
Have you got any problems. You can choose a base class and add specializations: GlowingRedCube extends GlowingCube extends Shape , but then you get a very wide set of classes and an inflexible set of things (what if you want to make SoftRedCube , but save any methods that you defined for your existing type red cube?)
You can just have a Cube and have lighting and shape properties, but then you wonโt get a good compiler type check: if you have the Room.lightUp() method and need to pass it to Cube , then you need to check whether this type includes any lighting ! If you can only pass it Illuminated , then the compiler will stop you as soon as you try.
Protocols allow you to separate this: GlowingRedCube can implement the Illuminated protocol, the Colorful protocol, and the Shape protocol. Due to protocol extensions, you can enable functionality by default, so you do not need to select a hierarchy level to join it.
struct GlowingRedCube: Shape, Colorful, Illuminated {
Effectively, protocols allow you to attach behavior to an object, regardless of what else this object does. That's why they are used for things like delegate protocols and data sources: even if you basically bind these things to the ViewController , the underlying object doesn't matter, so you can be flexible about how you implement it.
Swift uses the Swift protocol much more than just the basics: they are extremely powerful because they can be tied to several different code constructs: classes, structures, and enumerations. This allows you to really get closer to the programming protocol. There was a great video about this approach from WWDC last year , but it helps to spend some time trying some different object structures to get a feel for the problems first.
Ian barber
source share