Only 15% of iOS developers get the right answer 😧

Hi 👋

It’s the beginning of a new week, how about we start it with a little challenge?

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

And I gave 4 potential answers for what this code would print:

  1. “B: 100”

  2. “A: 100”

  3. “B: 10”

  4. “A: 10”

At the end of the day, out of 850 answers, only 15% of iOS developers had managed to get the right answer!

So before you scroll down to find out what the correct answer is, please take a few seconds to read the code attentively, try to figure out what your answer would be and, most importantly, what’s the reasoning behind the answer you’ve chosen.

👇

👇

👇

👇

👇

👇

👇

👇

Alright, here’s the correct answer:

So why is “B:10” the correct answer?

What’s happening here is that this code actually mixes two different mechanisms:

The implementation of the method is dynamically resolved (i.e. it depends on the type of the instance at runtime)

The default value of the argument is statically resolved (i.e. it depends on the type of the variable at compile time)

And that’s why we end up with this weird result, that contains elements from both implementations of the method 🤯

So the lesson here is to be weary of providing a default value to an argument when you’re working with a class!

(Unless that method is either private or final)

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

I wish you an amazing week!

❤️

Previous
Previous

Here are 5 tips you can start using today 😎

Next
Next

Here’s my second (traditional) newsletter 📮