'Swift & SwiftUI - Conditional global var

I want to make a global variable in Swift, so that its Data is accessible to any view that needs it. Eventually it will be a var so that I can mutate it, but while trying to get past this hurdle I'm just using it as let

I can do that by putting this as the top of a file (seemingly any file, Swift is weird):

let myData: [MyStruct] = load("myDataFile.json)

load() returns a JSONDecoder(). MyStruct is a :Hashable, Codable, Identifiable struct

That data is then available to any view that wants it, which is great. However, I want to be able to specify the file that is loaded based on a condition - I'm open to suggestions, but I've been using an @AppStorage variable to determine things when inside a View.

What I'd like to do, but can't, is do something like:

@AppStorage("appStorageVar") var appStorageVar: String = "Condition1"
if(appStorageVar == "Condition2") {
    let myData: [MyStruct] = load("myDataFile2.json")
}
else {
    let myData: [MyStruct] = load("myDataFile.json")
}

I can do this inside a View's body, but then it's only accessible to that View and then I have to repeat it constantly, which can't possibly the correct way to do it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source