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:
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?
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.
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!