1

I'm struggling with passing an variable to a class.

I have a class with different settings I store. The data is available and might be changed on different views.

class UserData: ObservableObject {
    @Published var ZipCode = "DK6700"   
}

The class is on my main view initialised as StateObject:

struct ContentView: View {
    @StateObject var SavedData = UserData()

    var body: some View {
        NavigationView {
        ChartView()
        }
        .edgesIgnoringSafeArea(.bottom)
        .environmentObject(SavedData)
    }
}

I call the Struct ChartView() where UserData is initialised as

@EnvironmentObject var SavedData: UserData
@ObservedObject var dataModel = DataModel()

and from the corresponding View, i can access the stored ZipCode. So far so good. The ChartView calls another class, where I download data in JSON format. This works as well, but I need the stored ZIP code in this class, and I can't figure out how to pass it. Currently ZIP is hardcoded in the DataModel, and works, but it should be the stored value instead.

My DataModel():

class DataModel: ObservableObject {
    @EnvironmentObject var SavedData: UserData
    @MainActor @Published var Data: [MyData] = []
    var ZIP:String = "3000"

    @MainActor func reload() async {
        let url = URL(string: "https://MyURL?zip=\(ZIP)")!
        let urlSession = URLSession.shared

        do {
            ...
        } catch {
            ...
        }
    }   
}

Any suggestions to get the stored ZIP code to my DataModel Class?

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
Lubker
  • 15
  • 5
  • 1
    You cannot use `EnvironmentObject` in a "normal" class like you do in `DataModel`, it is only used in `Views`. You have to read how to use `ObservableObject`. Have a look at this link, it gives you examples of how to use `ObservableObject` and manage data in your app https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app it is easy to understand, just copy and paste the example code to your app. – workingdog support Ukraine Jan 12 '23 at 22:46
  • Please use camel case on your properties in the future like savedData, data, zip and zipCode. That's the Swift standard and will make everyone reading your code much happier. :) – Marcy Jan 12 '23 at 23:57

1 Answers1

1

How about changing your function signature to

@MainActor func reload(for zipCode: String) async {

and passing it in when you call the function?

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160