Why it throw ab error as a "Cannot find 'state' in scope" in SwiftUI project?

I have small SwiftUI app, and it throw an error like "Cannot find 'state' in scope" for this line

 Register(state: state)

I guess it must be like that, but it is throw an error, I do not know what I missed? Any idea?


struct Register: View {

   
  @ObservedObject private var viewModel: RegisterViewModel
   
   init(state: AppState) {
   self.viewModel =RegisterViewModel(authAPI: AuthService(), state: state)
   }
   
  var body: some View {
}
}

struct Register_Previews: PreviewProvider {
   
  @ObservedObject private var viewModel: 
RegisterViewModel
  @State var pushActive = false
   
   init(state: AppState) {
   self.viewModel = RegisterViewModel(authAPI: AuthService(), state: state)
   }

   
  static var previews: some View {
    Register(state: state)
  }
}

class RegisterViewModel: ObservableObject {
 
  @Published var state: AppState
   
  init(authAPI: AuthAPI, state: AppState) {
    self.authAPI = authAPI
    self.state = state
  }
   
}

}
Answered by Claude31 in 706402022

I simplified code to have something that compiles, but that could be adapted to your case easily:

class RegisterViewModel: ObservableObject {
    
    @Published var state: Int
    
    init(state: Int) {
        self.state = state
    }
    
}

struct Register: View {

    @ObservedObject private var viewModel: RegisterViewModel
    
    init(state: Int) {
        self.viewModel = RegisterViewModel(state: state)
    }
    
    var body: some View {
        Text("Hello")
    }
}

struct Register_Previews: PreviewProvider {
   
    static var state: Int = 0
  @ObservedObject private var viewModel: RegisterViewModel
  @State var pushActive = false
   
   init(state: Int) {
   self.viewModel = RegisterViewModel(state: state)
       Register_Previews.state = state
   }

   
  static var previews: some View {
    Register(state: state)
  }
}

i would try to declare a

var state: AppState

in struct Register

and have a simple init()

Accepted Answer

I simplified code to have something that compiles, but that could be adapted to your case easily:

class RegisterViewModel: ObservableObject {
    
    @Published var state: Int
    
    init(state: Int) {
        self.state = state
    }
    
}

struct Register: View {

    @ObservedObject private var viewModel: RegisterViewModel
    
    init(state: Int) {
        self.viewModel = RegisterViewModel(state: state)
    }
    
    var body: some View {
        Text("Hello")
    }
}

struct Register_Previews: PreviewProvider {
   
    static var state: Int = 0
  @ObservedObject private var viewModel: RegisterViewModel
  @State var pushActive = false
   
   init(state: Int) {
   self.viewModel = RegisterViewModel(state: state)
       Register_Previews.state = state
   }

   
  static var previews: some View {
    Register(state: state)
  }
}

Why it throw ab error as a "Cannot find 'state' in scope" in SwiftUI project?
 
 
Q