Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a class1 which is having many variable and also having one function within a class1.I am calling the function from another class class2.function triggered but i cannot access variable of class1.

here is the sample code

class ViewController: UIViewController {

   var Flat:String?
    var Flong:String?
    var Tlat:String?
    var Tlong:String?
    override func viewDidLoad() {
        super.viewDidLoad()

     Flat = "flat value";
    Flong="flong value";
    Tlat="Tlat value";
    Tlong="tlong value";

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func calculation()
    {
       print("origin_lat new(Flat)")
        print("origin_lng new(Flong)")
        print("dest_lat new(Tlat)")
        print("dest_lng new(Tlong)")
    }

}

I am calling calculation method from another class Collectionviewcell click function

var mycontroller : ViewController = ViewController()

  mycontroller.calculation()

Why i could not access the values anyone help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
271 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can also reach other controller's variables with defining global variables like this way:

class Class1ViewController: UIViewController {
    struct GlobalVariables{
        static var Flat:String?
        static var Flong:String?
        static var Tlat:String?
        static var Tlong:String?
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        Flat = "flat value";
        Flong="flong value";
        Tlat="Tlat value";
        Tlong="tlong value";
    }
  ...
}

And you can use these variables in another view controller:

class Class2ViewController: UIViewController 
{
 ...
    print(Class1ViewController.GlobalVariables.Flat)
    print(Class1ViewController.GlobalVariables.Flong)
    print(Class1ViewController.GlobalVariables.Tlat)
    print(Class1ViewController.GlobalVariables.Tlong)
 ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...