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

SwiftUI ternary conditional operator

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

SwiftUI conditionally applied modifiers

The result is:

How to conditionally apply a modifier to a view in SwiftUI.
How to conditionally apply a modifier to a view in SwiftUI.
SwiftUI conditionally applied modifiers example gif

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:

SwiftUI VStack example

You are writing the body of a ViewBuilder closure (which is a functionBuilder). In fact, the VStack init is:

SwiftUI VStack init

At some point SwiftUI turns the Hello World snippet here above into a call to:

SwiftUI ViewBuilder build block example

Through xCode you can see that ViewBuilder closures implement other interesting methods:

SwiftUI ViewBuilder buildIf buildEither

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

SwiftUI function to conditionally apply modifiers to a view

We can now rewrite the star example using this function:

SwiftUI conditionally apply modifiers improved example

You can even write another simpler function in order to simply include/exclude a modifier (basically a function with just the if branch):

SwiftUI function to conditionally apply modifiers to a view 2

For example, you might want your image to be clipped when a specific condition is met:

SwiftUI conditionally apply modifiers improved example

Here is the complete GIST:

SwiftUI conditionally apply modifiers complete GIST

Passionate iOS developer for almost six years. SwiftUI/Combine early adopter. Author of SwiftUI NavigationStack https://bit.ly/2H6YjQS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store