Largely, it's hierarchy of types. Lets say you have an object representing a GlowingRedCube
, but you want to have that type used in lots of generic code that cares about:
- Different Shapes -
Cube
extends Shape
- Different Colors -
Red
extends Colorful
- Different type of illumination -
Glowing
extends Illuminated
You're in trouble. You could chose a base class and add specialisations: GlowingRedCube
extends GlowingCube
extends Shape
, but then you get an very wide set of classes, and an inflexible set of things (what if you wanted to make a SoftRedCube
, but keep any methods you've defined for your existing type of red cube?)
You could just have Cube
and have illumination and shape be properties, but then you don't get nice compiler type checking: if you have a Room.lightUp()
method and have to pass it a Cube
, you then need to check whether that type includes any illumination! If you could only pass it an Illuminated
then the compiler would stop you as soon as you tried.
Protocols allow you to separate this: GlowingRedCube
can implement the Illuminated
protocol, the Colorful
protocol and the Shape
protocol. Because of protocol extensions, you can include default implementations of functionality, so you don't have to choose a level of hierarchy to attach it to.
struct GlowingRedCube: Shape, Colorful, Illuminated {
// ..
}
Effectively, protocols allow you to attach behavior to an object, regardless of what else that object does. That's exactly why they're used for things like delegate and datasource protocols: even if you're mostly attaching those things to a ViewController
, the underlying object isn't relevant, so you can be flexible about how you implement.
There's a lot more to using protocols in Swift than just the basics though: they are exceptionally powerful because they can be attached to a number of different code constructs: classes, structs and enums. This allows you to really approach programming protocol first. There's a great video on this approach from WWDC last year, but it helps to have spent some time trying some different object structures yourself first to get a feel for the problems.