1

How can I refresh an environment var in SwiftUI? It is easy to update any object that's a part of an environment object, but it seems like there should be a way to re-initialize.

struct reinitenviron: View{
    @EnvironmentObject private var globalObj: GlobalClass
    var body: some View{
        Text("refresh").onTapGesture {
            globalObj = GlobalClass() //error here
        }
    }
}

The following gives an error that globalObj is get only. Is it possible to re-initialize?

1
  • No, it is not. If you need to reinit something, make it a property of the EnvironmentObject Commented Jul 6, 2022 at 20:53

1 Answer 1

2

A possible solution is to introduce explicit method in GlobalClass to reset it to initial state and use that method and in init and externally, like

class GlobalClass: ObservableObject {
  @Published var value: Int = 1

  init() {
    self.reset()
  }
  
  func reset() {
    self.value = 1
    // do other activity if needed
  }
}


struct reinitenviron: View{
    @EnvironmentObject private var globalObj: GlobalClass
    var body: some View{
        Text("refresh").onTapGesture {
            globalObj.reset()            // << here
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.