skip to content

In SwiftUI, how do you write a custom ViewModifier, and when is it better than a View extension that only chains modifiers?

level: middleimportance: must knowfreq 62%

answer

  1. a struct with one requirement
  2. content is a proxy, not the view
  3. modifier(_:) returns ModifiedContent
  4. extension for the call site
  5. stored properties and @State live in the struct

basics

~20 s

A ViewModifier is a struct whose body(content:) wraps the incoming view; a View extension that calls modifier(_:) exposes it. A plain extension suffices for a stateless chain; the struct earns its place when it keeps @State or reads the environment.

solid answer

~40 s

I conform a struct to `ViewModifier` and implement `body(content:)`, where `content` is a proxy for whatever view the modifier is applied to, and I return it wrapped in the shared modifiers. Calling `.modifier(CardSurface())` produces a `ModifiedContent<Self, CardSurface>`, and Apple's documented idiom is to hide that call behind a `View` extension so call sites read `.cardSurface()`. If the shared code is only a fixed chain of built-in modifiers, a `View` extension returning `some View` does the same job with less code. I reach for a modifier type when it needs its own `@State` (a tap-to-reveal balance, a press highlight), reads `@Environment` values, or should be a named value I can pass around or combine with `concat(_:)`.

code

swift · 27 lines
swift
import SwiftUI

struct RevealOnTap: ViewModifier {
    @State private var isRevealed = false

    func body(content: Content) -> some View {
        content
            .blur(radius: isRevealed ? 0 : 8)
            .onTapGesture { isRevealed.toggle() }
    }
}

extension View {
    func revealOnTap() -> some View {
        modifier(RevealOnTap())
    }
}

struct BalanceRow: View {
    let amount: String

    var body: some View {
        Text(amount)
            .font(.title2.monospacedDigit())
            .revealOnTap()
    }
}

go deeper

for a junior

Know the shape: a struct conforming to ViewModifier with body(content:), applied with modifier(_:) and usually exposed through a View extension.

for a middle

Explain what content is (an opaque proxy), what modifier(_:) returns (ModifiedContent), and the concrete reason to choose a type over an extension: storage such as @State or environment reads.

for a senior

Show judgment in review: reject modifier types that add nothing over an extension, keep the type private behind the extension, and spot designs that wrongly expect a stateful modifier to share state.

for a principal

Frame modifiers as one tool in a component layer: cross-cutting treatments any view can take, as opposed to controls that deserve a style protocol or composites that deserve a container view.

## What a ViewModifier is In SwiftUI a **view modifier** is anything that takes a view and produces a different version of it. The built-in ones (`padding(_:)`, `background(_:in:fillStyle:)`, `font(_:)`) are methods on `View`. The **`ViewModifier` protocol** lets you write your own as a type. Apple's documentation describes it as "a modifier that you apply to a view or another view modifier, producing a different version of the original value", and its article *Reducing view modifier maintenance* gives the motivation: when the same group of modifiers is repeated across many screens, a small design change means editing every copy. Collecting them in one modifier gives you a single place to change. The protocol has one requirement you write yourself: - **`body(content:)`** returns `some View`. It is a builder method, so you can use `if`, stacks and several modifiers inside it. - **`Content`** is the type of the `content` parameter. It is an opaque proxy for the view the modifier is applied to: you can wrap it, place it in a stack or overlay it, but you cannot inspect its concrete type or reach its properties. - **`Body`** is the associated type that the compiler infers from your `some View` return. `ViewModifier` is declared `@MainActor @preconcurrency`. Apple's documentation notes that a type which declares the conformance in its base declaration inherits main-actor isolation, while declaring it in an extension leaves the type nonisolated. ## Writing one and exposing it Applying a modifier type is done with **`modifier(_:)`**, which returns `ModifiedContent<Self, T>`: a new view value that pairs the original content with your modifier. Nothing is mutated; the original view is wrapped. Because `.modifier(CardSurface())` reads awkwardly, the documented idiom is a `View` extension: ```swift struct CardSurface: ViewModifier { var isHighlighted = false func body(content: Content) -> some View { content .padding(16) .background(.background, in: .rect(cornerRadius: 12)) } } extension View { func cardSurface(highlighted: Bool = false) -> some View { modifier(CardSurface(isHighlighted: highlighted)) } } ``` The extension gives a fluent call site, argument labels and default values, and lets the modifier type itself stay `private` or `fileprivate`. ## When an extension alone is enough Many shared treatments are just a fixed chain: a caption font plus a secondary colour, a corner radius plus a shadow. For those, a `View` extension that returns `some View` is all you need: ```swift extension View { func captionStyle() -> some View { font(.caption).foregroundStyle(.secondary) } } ``` This is shorter, and nothing is lost: the extension has no storage of its own, and none is needed. ## When a modifier type is worth it | Need | View extension only | `ViewModifier` type | |---|---|---| | Fixed chain of built-in modifiers | Yes | Works, more code | | Parameters with labels and defaults | Yes | Yes | | Private `@State` kept between updates | No | Yes | | Reading `@Environment` values | No | Yes | | A named value you can store, pass or `concat(_:)` | No | Yes | The decisive row is **storage**. An extension is a function: it runs and returns a view, so it has nowhere to keep a value across body updates. A modifier type is a struct with its own `body(content:)`, so it can declare `@State` and `@Environment` properties the way a view does. In a banking app, a "tap to reveal the balance" treatment needs a private `isRevealed` flag; that flag can live in a modifier type, never in a plain extension. Each place the modifier is applied gets its own copy of that state, tied to that position in the view hierarchy. ## Shaping the modifier as API Apple's article advises naming a custom modifier "to reflect the purpose of the collection", which matters more once twenty screens call it: - **Name the intent, not the recipe.** `.cardSurface()` survives a redesign; `.whiteRoundedShadow()` does not. - **Keep the struct private** and make the `View` extension the only public entry point, so every call site goes through the same defaults. - **Expose few parameters, with defaults.** Each parameter is a way for screens to drift apart; add one only when two real screens need different values. - **Keep it composable.** A modifier type is itself a value: `concat(_:)` combines two modifiers into one `ModifiedContent`, which helps when a design-system treatment is built from smaller ones. ## Pitfalls reviewers catch 1. **Wrapping instead of mutating.** Every modifier, yours included, wraps the content in a new value; the order you apply them in matters, which is a layout question rather than a design-system one. 2. **Over-engineering.** A modifier type with no properties and a three-line body adds a type without adding capability; an extension is clearer. 3. **Leaking the type.** Making the struct public when only the extension is meant to be API invites call sites that bypass your defaults. 4. **Expecting shared state.** Two views that apply the same stateful modifier do not share its `@State`; shared state has to come from a model or an environment value supplied from outside.

  • If two rows both call .revealOnTap(), do they share the revealed state?
    No. The `@State` belongs to each application of the modifier at its own position in the view hierarchy, so every row keeps its own `isRevealed` for as long as that row keeps its identity. If the screen needs one switch for all balances, the flag has to come from outside, for example a model or an environment value set by an ancestor.
  • How does main-actor isolation apply to a custom ViewModifier in Swift 6 mode?
    `ViewModifier` is declared `@MainActor @preconcurrency`. Apple's documentation says a type that declares the conformance in its base declaration inherits that main-actor isolation, and declaring the conformance in an extension instead leaves the type nonisolated. View-building code normally belongs on the main actor, so the default is usually what you want.
  • Why does Apple pair a ViewModifier with a View extension instead of calling modifier(_:) everywhere?
    The extension gives the modifier a discoverable, fluent call site that reads like a built-in (`.captionTextFormat()`), lets you add argument labels and defaults, and keeps the modifier type private if you want. Apple's article on reducing view modifier maintenance presents exactly this pair: collect the modifiers in one type, then extend `View` with a method that applies it.

  • A ViewModifier changes the original view in place instead of wrapping it.
  • A View extension function can keep its own @State between updates.
  • Every shared style must be a ViewModifier type; plain extensions are bad practice.
  • The content parameter exposes the wrapped view's concrete type and properties.
  • modifier(_:) erases the result to AnyView.