Slavic the Slavic
Slavic the Slavic

Reputation: 411

How to change a variable in a different class? (iOS, Swift)

I have 3 View Controllers in Storyboard. They're named "Letters", "Numbers", and "Other".

What I want is a variable that changes based on which category was used last.

Ex: The user goes to the Letters View Controller (var categories = "Letters"), and then to the Other View Controller, and is able to use the "categories" variable (which is still "Letters"). User goes to the Numbers View Controller (var categories = "Numbers"), and then to the Other View Controller, and is able to use the categories variable (which is now "Numbers").

I'm not sure if my question and example are clear enough, and if they aren't feel free to ask, and I'll try to further explain.

Any help would be greatly appreciated.

Thanks in advance.

Upvotes: 1

Views: 3899

Answers (2)

Rhuari Glen
Rhuari Glen

Reputation: 507

The best way to do this is by creating a variable named categories on each of your view controllers and assigning a value to this before you present your next view controller.

EXAMPLE:
Letters View Controller

var categories = [String]()

    func goToNextViewController()
    {
      let numbersVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "numbersVC")
      numbersVC.categories = self.categories
      self.presentViewController(numbersVC, animated: true, completion: nil)
    }

Numbers View Controller

var categories = [String]()

Upvotes: 0

Lou Franco
Lou Franco

Reputation: 89142

There are lots of ways to do this, but the key concept is that you don't change variables in other classes, you change things in instances (objects) of classes.

I am going to try to keep this simple.

So, you could make a class that has App State kinds of things

public class AppState {
    public var category: String? = nil
    public static let shared = AppState()
}

Then, anywhere in your code, you can do

AppState.shared.category = "Letters"

Or

if let currentCategory = AppState.shared.category {
    // use currentCategory here
}

Doing this is not the best way, but it will work and it's simple. To go a little further, you could learn about dependency injection. Using that, there would not be a global shared instance, but instead you would pass the appropriate AppState object to objects that needed it.

Upvotes: 3

Related Questions