I have a single instance of a class that contains struct that I want to be able to be mutated through out the runtime of my program, I also want the getter and settter to be accessible from the global scope and was wondering how I'd go about doing so
The simple answer:
@MainActor // lets you access this var from any SwiftUI View without locks
let shared = GlobalState()
@Observable // it's important for this to be observable or dependency tracking won't work
final class GlobalState {
var foo: MyStruct = MyStruct() // mutations of fields of the struct trigger the setter.
}
This comes with all the drawbacks of singletons, and I would advise against doing this unless your program is very simple. There's many resources online about singletons you can find for yourself, so I'll just say that SwiftUI @Entry + Environment are a much better alternative for data that has a sane default (which it must have if you're considering globally scoping it already).