SwiftUI: Why You Need AnyView
AnyView’s “performance problems”… and solutions.
AnyView has problems. Really. Ask any seasoned iOS developer and they’ll tell you that AnyView has problems.
Problems so significant, in fact, that the majority of SwiftUI developers completely ignore it and some shops prohibit its use altogether.
It’s that bad.
Ask why it’s bad, however, and most developers will begin to avert their eyes, stare off into the distance, and start mumbling something about how it “destroys” view hierarchies and kills performance.
Press the question even further and they’ll start to hem and haw, and then, finally, admit that they don’t know why it’s bad or how it kills performance. Just that they’ve been told that it’s bad.
And didn’t Apple say something about avoiding it in one of their WWDC videos?
They did. But more on that later.
But the truth is that AnyView isn’t bad. And that there are valid reasons for its existence. True, there are a few special cases where using it can cause performance problems. But you know what?
You can trigger those same exact issues in “normal” SwiftUI code without using AnyView.
In fact, I’m willing to bet that you probably have those problems in your existing code base right now. We’ll get into that later as well.
Before we move on I want to mention that the recommendations made here are not just my opinions, but are based on actual data obtained by testing and examining a multitude of use cases, as well as by instrumenting several SwiftUI test projects and recording the results.
The main project is available from my GitHub repository. Feel free to download it and follow along.
So are you ready?
If so, then let’s take a deep dive into AnyView, see what problems it might have, see how we can mitigate them if they exist, and then see how we can use AnyView in our own code, safely and securely, to our own benefit.
First, let’s see what Apple has to say in their developer documentation.