Search code examples
stringvariablesglobal-variablesswift5xcode11

How to make a variable that is accessible and changeable by all files in project


Say I wanted to have a string containing the user's name, and I wanted to be able to access and/or change that variable across all swift files. For example, I have a view controller file for the user's profile page and a settings page - I want to be able to access and change that variable in either of those files. I have tried making a class file, but whenever I make an instance of that class in my view controller, I am able to access the default value of the variable in that class, but I am not able to permanently change its value.

So essentially, I want to be able to declare a global variable that is accessible by all files in my project, and can be changed by all files in my project.


Solution

  • Nevermind, I decided to use user defaults to save my variables, and I can then retrieve them from any file within the project.

    For example:

    //Declare this inside your class
    let defaults = UserDefaults.standard
    //Take any variable like this
    var name: String = "Bill"
    //and save them to UserDefaults
    defaults.set(name, forKey: "name")
    

    You can then access the variable in another class(or in the same class, just drop the "let" before "name") by calling:

    if let username = defaults.string(forKey: "name"){
    let name = username
    

    The variable is accessible by the unique key you give it when calling the defaults.set() function. You can change the value the same way you initially declared it.