This small mistake will crash your SwiftUI app 🧨
Hi 👋
Last week this newsletter reached 2,500 subscribers 🥳
It’s a really cool milestone and I’m really happy to see that my latest outlet keeps growing month after month!
I have some cool ideas for the content of the upcoming weeks, I hope you’ll like it 😀
And before we go into the topic of this email, I have a big thank you to my sponsor this week: Proxyman 🧑🚀
Advertisement
Sponsors like Proxyman really help me grow my content creation, so if you have time please make sure to check out this product: it’s a direct support to my content creation ☺️
What do you think this code will do? 🤨
Please don’t jump to a new Xcode project to try it out, instead try to take a minute to reason about it.
To help you, I’ll narrow it down to 3 options:
It won’t build 🙅🏻♂️
No padding will be applied 😶🌫️
It will crash 💥
As you can imagine, I asked that same question on social media last week. Here the results:
The majority of iOS developers seem to believe that what I wrote is not valid Swift code, and so will not be able to compile.
But try it out and you’ll see that this code will actually build just fine!
However, if you try to run it you will also see that your SwiftUI app will crash quite rapidly 🧨
This means that we have two problems on our end:
First, we’ve discovered that such a small mistake in our UI code can lead to a crash, without any prior warning whatsoever.
I’m sure that knowing this, you will definitely pay more attention in future code reviews!
But we’re also left with quite a mystery on our hands: how did this mistake end up causing our app to crash?
The key to solving this mystery is to understand what’s happening when we call padding()
without the leading `.` character.
If you have a look at the declaration of the method padding()
, you’ll see that it’s declared inside an extension of View.
This information is significant, because it means that when we call padding()
inside the body
of our ContentView
, we’re actually calling self.padding()
:
What’s happening here is that the call to self.padding() has the effect of recursively adding the ContentView
as a child view of itself 😳
This means that when SwiftUI calls the body
property of our ContentView
, the call will trigger an infinite recursion that will result in our app crashing 🤯
So what’s the lesson here?
Unfortunately, the main lesson is that even modern frameworks like SwiftUI leave enough room for mistakes that have bad consequences…
But at least, now that you’ve read this email you are aware of this issue’s existence and so you will be less likely to make it yourself and more likely to spot it if others make it 😌
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!
❤️