DEV Community

Caleb Hearth
Caleb Hearth

Posted on • Originally published at calebhearth.com on

How I Model SwiftUI Views

The approach I take to defining ViewModels for SwiftUI was heavily inspired by Paul Hudson’s post Introducing MVVM into your SwiftUI project. In it, he advocates for defining class ViewModel inside an extension to the relevant view. By naming each view’s MVVM class ViewModel, it can always be referenced directly by that name instead of remembering to use ContentViewViewModel, UserListViewModel, etc. I take it a step further and simply name the class Model:

import SwiftUICore

extension ContentView {
 @MainActor @Observable class Model {
    // properties and functions
  }
} 
Enter fullscreen mode Exit fullscreen mode

And each view has an instance of its ViewModel, and hopefully nothing else.

struct ContentView: View {
  @State private var model: Model = .init()
} 
Enter fullscreen mode Exit fullscreen mode

In practice, useful property wrappers like @Binding or @Environment will get hoisted into the view. I’ve also had absolutely zero luck incorporating this fully with SwiftData. In theory you can build your own Query with Predicate<PersistentModel>

Read More

Top comments (0)