dan martin
dan martin

Reputation: 1317

Swift - change variable in another view controller, without knowing the class name?

Let's say I have a function in viewController1, that changes a variable in whichever view controller the function is called from (in this case viewController2)

What I've been attempting -

declaring the function in viewController1:

func changeVariable(controller: UIViewController) {
    controller.variable = "Hello"
}

calling the function from viewController2:

changeVariable(self)

However, this gives me an error when declaring the function, telling me that UIViewController has no member named 'variable'.

If I then change the function to:

func changeVariable() {
    viewController2.variable = "Hello"
}

It works. But, I don't know which view controller is calling the function beforehand (it could be viewController3, for example), so I can't explicitly state that in the function.

Does anyone know how I can make this work?

Thanks a bunch.

Upvotes: 0

Views: 3596

Answers (1)

Aaron Brager
Aaron Brager

Reputation: 66302

This is what protocols are for: defining a common language between classes when you don't want to share their exact name.

You could define a CommonVariable protocol that describes a variable string:

protocol CommonVariable: class {
    var variable: String { get set }
}

Then edit your ViewController2 definition to conform to this protocol:

class ViewController2: UIViewController, CommonVariable {
    var variable = ""
}

And edit your ViewController1 method to accept a CommonVariable as the parameter:

class ViewController1: UIViewController {
    func changeVariable(controller: CommonVariable) {
        controller.variable = "Hello"
    }
}

Now this method knows nothing about controller except that it's a class with a string called variable.

As a result, you will be able to call the method from ViewController2 without knowing the class name:

func someFunc() {
    viewController1.changeVariable(controller: self)
}

As a side note, CommonVariable, variable, ViewController1, and ViewController2 are all bad names. Not sure if you're actually using these names, but you should aim for something more descriptive.

Upvotes: 5

Related Questions