Okay, so I’ve been messing around with Swift lately, and I bumped into this thing called “protocol boxing.” It sounded kinda fancy, but it’s actually pretty straightforward once you get the hang of it. Let me walk you through how I figured it out.

My Little Experiment
First, I made a simple protocol. Think of it like a blueprint for what something should be able to do. I called it Drawable, and all it did was say, “Hey, whatever uses this protocol needs a draw() method.”
Then, I created a couple of structs that followed this protocol. One was called Circle, and the other was Square. Both of them had their own way of “drawing” themselves – basically, just printing out what they are.
The Problem I Ran Into
Now, here’s where it got interesting. I wanted to make a list – an array – of these Drawable things. My goal was to have both circles and squares in the same list, and then just loop through them and tell each one to draw(). Simple, right?
But when I tried to make an array of type [Drawable] and stuff both Circle and Square instances into it, Swift started complaining. It was like, “Whoa, hold on! These things are different sizes!”
The “Aha!” Moment
That’s when I learned about this “protocol boxing” thing. It’s basically like putting each of these Drawable things into its own little box. Each box is the same size, even though the things inside might be different. These “boxes” are actually called existential containers, which the compiler will generate for us, it will automatically box all the conformed types and erase their specific type information, so they can be stored in the same array.

So, I changed my array to store Any that conforms to the Drawable protocol. And guess what? It worked!
Putting It All Together
I ended up with something like this(not the exactly same code, it is a similar one):
- I had my Drawable protocol.
- I had Circle and Square structs that followed the Drawable protocol.
- I made an array called drawables, And I can put both circles and squares inside.
- Finally, I looped through the drawables array and called draw() on each item. Each one printed out its own thing, even though they were all mixed together in the same list.
So, yeah, that’s my little adventure with protocol boxing in Swift. It’s all about making things that are kind of different act the same way, so you can treat them as a group. Pretty neat, huh?