Why is SwiftUI.ViewModifier a useful concept?

I was just watching this WWDC video on SwiftUI:

and their usage of SwiftUI's ViewModifier finally pushed me to post this question I've always had. I use SwiftUI exclusively and constantly in a variety of ways, but I don't use ViewModifier at all. The example code in the video in which they are using ViewModifier is this:

struct ExpirationModifier: ViewModifier {
    var date: Date
    func body (content: Content) -> some View {
        content.opacity(date < .now ? 0.3 : 1.0)
    }
}

the way I would achieve this same thing is simply this:

extension View {
    func expiredAppearance (basedOn expirationDate: Date) -> some View {
        self.opacity(expirationDate < .now ? 0.3 : 1.0)
    }
}

One aspect of my approach which I prefer is that my modifier is discoverable in code-completion, whereas the ViewModifier type floating in the namespace is not.

Are there advantages to using ViewModifier instead of directly extending View?

2 Likes

A ViewModifier is a struct and thus it can contain its own state which is vital for more complex scenarios.

And usually you offer an extension on view to make it more discoverable.

But sure, for the simple cases a function is enough ^^

2 Likes

For stateful modifiers, you can also use a separate View instead of a ViewModifier. Personally, I only use them when I need to pass them around. For example to AnyTransition.modifier(active:identity:)

I think under the hood SwiftUI uses ViewModifier to know if it's an "inert modifier" - aka if the modifier is currently not modifying anything about the view, so that it can apply some optimisations. SwiftUI is all about ergonomics, so if the team wanted us to use a whole extra struct, I'd think it's for good reason.

Do you know where I can find out more about how this works under the hood?

Unfortunately no, the first time I learned about inert modifiers was from the very WWDC video you linked. This is mostly my intuition, which I’m nonetheless pretty confident about. Sorry I couldn’t be of more help!

Terms of Service

Privacy Policy

Cookie Policy