title: can't set data to the variable when i parse json
body: <p>I am currently trying to set data I get from parsing my json to a variable in my <code>ViewController</code> from <code>RawDataCategory</code> file, which decodes json.</p>
  <p>Here is how I call a static method in <code>CategoryViewController</code></p>
  <pre><code>class CategoryViewController: UIViewController {
  
      @IBOutlet weak var tableView: UITableView!
      
      var categoryProducts: [Datum]? // this is the variable i want with data i get
      
      override func viewDidLoad() {
          super.viewDidLoad()
          
          
          tableView.dataSource = self
          tableView.delegate = self
    
          Datum.fetchProducts { (categoryProductsFromJSON) -&gt; () in   // here i call a static function.. i will paste the code below
  
              self.categoryProducts = categoryProductsFromJSON  //here i set value
  
              print(self.categoryProducts?[0].name) // if i try to print the value in the scope i can access it. and it shows with no problem
          }
  
              print(categoryProducts?[0].name)  //here is the problem. when i get out of the scope it return nil. 
     
      }
  }
  </code></pre>
  <p>I can access the variable in the scope but somehow when i try to call it outside it prints <code>nil</code>.</p>
  <p>Here is the static function (method) i call to get decoded json:</p>
  <pre><code>
      static func fetchProducts(_ completionHandler: @escaping ([Datum]) -&gt; ()) { 
  
          guard let url = URL(string: &quot;http://localhost:8888/dayhandan/public/api/v1/category/1&quot;) else { return }
  
          let session = URLSession(configuration: .default)
  
          let task  =  session.dataTask(with: url, completionHandler: { (data, response, error) -&gt; Void in
  
              if error != nil {
                  print(&quot;error&quot;)
                  return
              }
  
              do {
                  print(&quot;no error so far&quot;)
                  guard let data = data else { return }
  
                  let rawData = try JSONDecoder().decode(CategoryRawData.self, from: data)
  
                  DispatchQueue.main.async(execute: { () -&gt; Void in
                      completionHandler(rawData.data ?? [])
                  })
  
              } catch let err {
                  print(err)
              }
          })
          task.resume()
      }
  
  
  </code></pre>
  <p>I don't get any errors while i decode json. In fact I can pass it to my <code>ViewContoller</code>. There are no errors overall. <code>categoryProducts</code> just becomes nil when i call it outside the scope.</p>
  <p><strong>Is this a good way to use decoded data. if it is can someone help me to solve the issue. or can someone point at a good way to use decoded data. Thanks for your time</strong></p>