1

Is there a way to have a global state variable in SwiftUI? It would be nice to be able to have all my views subscribe to the same state. Is there some reason not to do this?

When I tried to declare a global variable with the @State decorator, the swift compiler crashed (beta software, am I right?).

zoecarver
  • 5,523
  • 2
  • 26
  • 56
  • 2
    I suggest to watch https://developer.apple.com/videos/play/wwdc2019/226/. `@EnvironmentObject` might be what you are looking for. – Martin R Jun 08 '19 at 06:58

2 Answers2

1

@State is only for managing local variables. The wrapper you're looking for is @EnvironmentObject. You could use this for theme color, orientation, subscribed or non subscribed users etc etc.

Joey Slomowitz
  • 179
  • 1
  • 12
1
var globalBool: Bool = false {
    didSet {

        // This will get called
        NSLog("Did Set" + globalBool.description)

    }

}


struct GlobalUser : View {
    @Binding var bool: Bool


    var body: some View {

        VStack {

            Text("State: \(self.bool.description)") // This will never update
            Button("Toggle") { self.bool.toggle() }
        }

    }

}

...
static var previews: some View {
    GlobalUser(bool: Binding<Bool>(getValue: { globalBool }, setValue: { 

    globalBool = $0 }))

}
lorem ipsum
  • 21,175
  • 5
  • 24
  • 48
savan patel
  • 254
  • 1
  • 5