5 Steps to Better SwiftUI Views

5 Steps to Better SwiftUI Views

As SwiftUI projects grow more complex, it’s common to find your views get larger and larger as you cram more functionality into them. In this article I’ll walk you through the underlying problem, and demonstrate five steps you can take to make your views simpler, smaller, and smarter – all demonstrated using a real SwiftUI project, so you have actual code to follow along.

[…]

Sponsor Hacking with Swift and reach the world's largest Swift community!

[…]

One way to fix this is to enable SwiftUI’s view builders, like this:

[…]

Of all the ways you can simplify your SwiftUI views, this is the one that I think is most effective: creating smaller SwiftUI views that have individual pieces of behavior, then composing them together into larger views.

[…]

Even better, we can go a step further because two marvelous Swift features combine here.

First, because all our SwiftUI views are automatically structs, we get a memberwise initializer.

[…]

A better idea is to wrap up your custom functionality as an extension to one of SwiftUI’s views, like this:

[…]

I find view extensions particularly useful for making platform adjustments. For example, if a view needed extra padding on iOS but not macOS, I might have a helper method like this one:

And now you can conditionally apply modifiers just for iOS, like this:

You can of course create other variants for macOS, watchOS, or whatever platform you’re targeting.

[…]

To summarize, we’ve looked at five ways to create simpler SwiftUI views:

[…]