t0re199 t0re199 - 4 months ago 8
Swift Question

How to set a variable value in another class in Swift

How can I add a value to a variable in a class

myClass2
from another class
myClass
in swift?

I have already tried something like
myClass2().myvariable = "value"
, but this didn't work; my variable value is still
nil
. here's the code:

myViewController2:

import UIKit

class myViewController2: UIViewController {

var myVariable : String?;

@IBOutlet weak var display: UITextField!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func showPressed(sender: AnyObject) {
display.text = myVariable;
}

}


ViewController:

import UIKit

class ViewController: UIViewController {

let myClassInstance = myViewController2();
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func toView2Pressed(sender: AnyObject) {

let view2 = self.storyboard?.instantiateViewControllerWithIdentifier("view2") as myViewController2;
self.navigationController?.pushViewController(view2, animated: true);
myClassInstance.myVariable = "my new value";
}

}

Answer

You're creating an instance of myViewController2 called myClass instance, but that's not the instance that you push onto the stack -- the instance being pushed is view2. So the last line in toView2Pressed should be,

view2.myVariable = "my new value"

You should delete the line, let myClassInstance = myViewController2(). It serves no purpose. You should also start your class names with a capital letter.

Comments