Sending variable between views & Classes

Hi All,

First post here. I am new to SwiftUi & app development and im struggling with passing data between views & classes. I have been following a tutorial but i want to add further functionality as a good way for learning.

I have a weatherView with the following code
Code Block
struct WeatherView: View {
@ObservedObject var weatherViewModel = WeatherViewModel()
private var city: Int = "2639577"
  var body: some View {
    ZStack {
      BackgroundView()
       
      VStack {
        if weatherViewModel.stateView == .loading {
          Show Loading
          }
        }
         
        if weatherViewModel.stateView == .success {
DO something
}
}

This call my WeatherViewModel class as following

Code Block
class WeatherViewModel: ObservableObject {
private var city = "city from WeatherView"
 private func getData() {
do something
}
}


Im really struggling to pass the city variable to the class. I need this to then call the API client.

Could anyone shed some light on how to this this please.

Thank you very much


Hi there,
you could just change the value inside the class using:
Code Block Swift
class WeatherViewModel: ObservableObject {
    @Published var city : String = "city name changed by view"
    func getCityData(){
        print("called")
    }
}
struct WeatherView: View {
    @ObservedObject var data = WeatherViewModel()
    var body: some View{
        VStack{
            Button(action: {
                data.city = "city name"
            }){
                Text("Change City")
            }
        }
    }
}

Does this help you?

Take care
David

Sending variable between views & Classes
 
 
Q