Trouble Setting a Variable in a Singleton

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?

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

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?

I don't know that "better" is the right word for this. It works. What you have above, does not work.

2 Likes

@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