iosswiftinstanceswift-class

Accessing class instance in swift


I've got a Graph class which is an UIView and I'm initializing it inside mainVC.swift:

class MainVC : UIViewController{
   let graph : Graph!

   override func viewDidLoad(){
      super.viewDidLoad()
      let data_x : [Double] = [...]
      let data_y : [Double] = [...]
      ...
      graph = Graph(frame: CGRect(...), color: ..., xData: data_x, yData: data_y, darkMode: ...)
      view.addSubview(graph)
      ...
      }

Now I would like to access function inside instance of the class which I've created in MainVC in different class (to populate data in TableView).

var g : Graph = MainVC.graph returns "Instance member graph cannot be used on type MainVC" I've also tried using static variable but there was an error.


Solution

  • This is one of the way which i known check it out.

    class MainVC {
       let graph : Graph! 
    }
    

    graph is a stored property is a constant or variable that is stored as part of an instance of a particular class.So you tried for accessing instance property not an instance of class.

    In your class MainVC make variable as static which holds instance

     static var graph: Graph?
    

    Then store instance of Graph in graph property in Graph class

      MainVc.graph = self
    

    Now you can use in another class where you access graph instance like

      MainVc.graph