We inherited some code that has a variable that begins in the "SwiftUI world", so to speak, and is copied over to a global variable in the "Swift world" for use in non-SwiftUI classes (POSOs? Plain Ol' Swift Objects?).
Here's a contrived example showing the basic gist of it. Note how there's an AppViewModel that maintains the state, and an .onChange that copies the value to a global var, which is used in the plain class DoNetworkStuff. I would like to weed out the redundant global var, but I kind of see why it was done this way--how DO you bridge between the 2 worlds? I don't think you can add a ref to AppViewModel inside DoNetworkStuff. I was thinking you could add a function to the AppViewModel that returns devid, and stash a ref to the function in a var for use whenever devid is needed., so at least you're eliminating the var value being stored in 2 places, but that might be confusing a year from now. I'm trying to think of a way to rewrite this without ripping out too much code (it could be that maybe it's better to leave it).
var gblDevID = "" //global var
class AppViewModel: ObservableObject {
@Published var devid = ""
...
}
struct ContentView: View {
@StateObject var appViewModel = AppViewModel()
var body: some View {
TextField("Enter device id", text: $appViewModel.devid)
.onChange(of: appViewModel.devid) { newVal in
gblDevID = newVal
}
...
}
}
class DoNetworkStuff {
func networkingTask() {
doSomeTask(gblDevID)
}
}
5
0
2.7k