boopxyz
(boop_xyz)
March 19, 2023, 5:06pm
1
Hi, so I have a class with variables and a shared variable for accessing
class MyVars {
static let shared = MyVars()
@State var temp: String = "..."
@State var humid: String = "..."
@State var model: String = "..."
}
and here I am setting it
class MyVars {
MyVars.shared.temp = res.temp
MyVars.shared.humid = res.humid
MyVars.shared.model = res.model
print(MyVars.shared.temp)
}
Yet, when I print it, it doesn't print what I just set it to.
Anyone got any ideas?
Jessy
(Jessy)
March 19, 2023, 5:17pm
2
Why do you have the impression that @State
should be used with a class that is not a View
? That impression is incorrect.
You can do this,
MyVars.shared._temp = .init(initialValue: "a")
but it's pointless.
1 Like
boopxyz
(boop_xyz)
March 19, 2023, 5:19pm
3
Well I am preforming a HTTP request to get data. I want to update the text with that data. So I used state to change the text. Is there a better way to do this?
Jessy
(Jessy)
March 19, 2023, 8:16pm
4
I don't know that "better" is the right word for this. It works. What you have above, does not work.
2 Likes
henrikac
(Henrik Christensen)
March 19, 2023, 8:26pm
5
@State
is meant mainly for View
in SwiftUI according to the docs .
What you could do is something like
class MyVars {
static let shared = MyVars()
var myVar1: String
var myVar2: String
private init() {
self.myVar1 = "..."
self.myVar2 = "..."
}
}
MyVars.shared.myVar1 = "..."
MyVars.shared.myVar2 = "..."
1 Like