SwiftUI tips and tricks
How to conditionally apply modifiers in SwiftUI
Leveraging the buildIf and buildEither functions to improve the readability of your code
When it comes to conditionally applying a modifier to a view in SwiftUI there are a couple of approaches, depending on your needs.
Ternary conditional operator
Well, if you know SwiftUI you are very likely already familiar with this kind of things. If you need to apply different instances of a specific modifier to a view, this is by far the most common and SwiftUI compliant way to do that. Let’s see a very simple example:
foregroundColor
modifier is Color.red
or Color.yellow
based on the value of condition
. Pretty straightforward.
But what if I liked conditionally including/excluding a modifier to a view?
ViewBuilder buildIf and buildEither power
Let’s say we have a resizable image and we want the image to either fit the parent or fill the parent, based on a condition. You can exploit the power of the ViewBuilder
buildIf
and buildEither
functions:
The result is:
Even if it’s hidden in the snippet above, you are leveraging function builders to get the result shown in the GIF.
Remember that when you write something like:
You are writing the body of a ViewBuilder
closure (which is a functionBuilder)
. In fact, the VStack
init is:
At some point SwiftUI turns the Hello World snippet here above into a call to:
Through xCode you can see that ViewBuilder
closures implement other interesting methods:
which are basically what you implicit use every time you write an if
or anif/else
statement in a ViewBuilder
closure (as I did in the example with the resizable star).
Let’s improve the solution
The solution shown for the star image problem works as expected, but it’s pretty annoying. The code is not that clean, there are some unnecessary lines of code replicated just to conditionally apply a modifier or to conditionally apply different modifiers to a view. And if you needed this kind of things more than once, your code would soon become messy and less readable. So, let’s create a function that helps us refactoring this situation:
We can now rewrite the star example using this function:
You can even write another simpler function in order to simply include/exclude a modifier (basically a function with just the if
branch):
For example, you might want your image to be clipped when a specific condition is met:
Here is the complete GIST: