ViewModifier vs AnyView

SwiftUI Junior Swift 5.1+ iOS 17+ Reviewed By Alok Singh

Pick the fix

Ten screens repeat the same padding, background and corner radius. Which reuse approach is best?

Options
Hint 1 of 1

Which option keeps the concrete view type?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A A CardStyle: ViewModifier plus extension View { func cardStyle() -> some View }

Correct. It is reusable and keeps concrete types.

Why not the others?
  • B A function that returns AnyView(content.padding()...). It works, but type erasure hides structure from SwiftUI's diffing.
  • C Copy the modifiers into each screen. Ten copies drift apart over time.
  • D Subclass a base view. SwiftUI views are structs; there is no inheritance.

30-second answer

A ViewModifier packages reusable styling or behaviour, applied with .modifier() or a View extension. It keeps concrete types, so SwiftUI can diff efficiently. AnyView erases the type, which hides structure from SwiftUI, can hurt performance, and makes identity harder to reason about.

Practise saying it · 30 s. No recording, just a timer

Explain ViewModifier vs AnyView.

Say your answer out loud, then check which of these points you covered:

  • Reusable styling
  • Keeps concrete types
  • AnyView erases types and hurts diffing

Deep dive

Expose a modifier through an extension: func cardStyle() -> some View.

Modifiers can hold @State and read the environment.

Use @ViewBuilder or generics instead of AnyView for conditional content.

AnyView is acceptable for truly heterogeneous collections, such as plugin views.

Common mistakes

  • Returning AnyView from helper functions by default.
  • Building conditional modifiers with if/else that change identity.
  • Huge modifier chains copied across files.

Senior take & follow-ups

Seniors explain type erasure's cost for diffing, not just style.

Follow-up questions

Think of your answer first, then open the hint.

  1. Can a ViewModifier have state?

    Show hint

    Yes, @State inside a modifier works.

  2. When is AnyView fine?

    Show hint

    Rarely: heterogeneous lists of unknown view types.

From the author

Catalog - UI

Made by the author: browse UIKit and SwiftUI components with live demos, and copy their code snippets into your project.

Suggest a fix if something here is wrong or out of date.