TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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

Reply to this topic…

You need to create an account or log in to reply.

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.