GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Passing @StateObject into ViewModel

Forums > SwiftUI

Hi everyone!,

I'm dealing with this and I would like to know the best approach and what would be needed to fix the problem that I have at this moment:

I have a View with two @StateObjects, User and ViewModel ObservableObject classes. I want to pass to the ViewModel the User instance in order to move all the logic into the ViewModel. This is what I tried:

struct SignUpView: View {
      @StateObject var newUser = User()
      @StateObject private var viewModel: ViewModel

      init() {
          let viewModel = ViewModel(newUser: newUser)
          _viewModel = StateObject(wrappedValue: viewModel)
      }

}

ViewModel:

extension SignUpView {
    @MainActor class ViewModel: ObservableObject {

        init(newUser: User) {
            self.newUser = newUser
        }

        @Published var newUser: User

    }
}

I'm getting 'self' used before all stored properties are initialized in the line:

let viewModel = ViewModel(newUser: newUser)

How should I handle this?

Thanks!

2      

hi,

this should do it ... just create the user first in the init:

struct SignUpView: View {
      @StateObject private var newUser: User
      @StateObject private var viewModel: ViewModel

      init() {
          let user = User()
          _newUser = StateObject(wrappedValue: user)
          let viewModel = ViewModel(newUser: user)
          _viewModel = StateObject(wrappedValue: viewModel)
      }

}

hope this helps,

DMG

2      

Thanks!

2      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.