Are private properties really private? 🤨

Hi 👋

There’s currently more than 750 subscribers to this newsletter, thank you all so much for your support 🥰

A new week is starting, how about we make it begin with a little challenge?

Last week I asked another (tricky) Swift question on Twitter:

And as you can see in the results of the poll, people where quite unsure about how to answer that question:

Just like last time, before you scroll down to find out what the correct answer is, please take the time to reason about the problem and try to come up with your own answer!

I can even provide a few additional precisions to help you in your thinking:

  • You cannot change anything in the way the class is implemented. It might as well be part of a binary framework

  • The fact that it is a class has no impact here, it could as well be a struct

Alright, if you’ve decided what your answer is now you can scroll down to find out the solution!

👇

👇

👇

👇

👇

👇

👇

👇

So as it turns out, it is possible to access a private property 🤯

This counterintuitive result can be achieved through runtime introspection, using a special type called a Mirror.

Here’s what the code looks like:

If you want to experiment with this code, it’s available on GitHub.

I had also made a video back in 2021 that explains this topic in more details, you can watch it on YouTube.

That’s all for this email, thanks for reading it!

If you’ve enjoyed it, feel free to forward it
to your friends and colleagues 🙌

I wish you an amazing week!

❤️

Previous
Previous

3 mistakes to avoid with Closures

Next
Next

How to write your first Unit Test