0

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.

1 Answer 1

1

You could change just change the global in an onChange on the AppStorage variable. This is an answer to your question, but you have the problem that no view is going to be updating itself when the global changes.

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

struct ContentView: View {
    @AppStorage("appStorageVar") var appStorageVar: String = "Condition1"
    var body: some View {
        Button("Change value") {
           appStorageVar = "Condition2"
        }
        .onChange(of: appStorageVar) { newValue in
            myData = load(newValue == "Condition1" ? "myDataFile.json" : "myDataFile2.json")  
        }
    }
}
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.