Im having a problem with my swift code. I am trying to set the array yearsLinks to a value inside my closure and I am able to do this and print it while I am still in the closure but when i try to print the array values outside of the closure, it returns an empty array. why is this?.
Please help, I want to set the array values, yearsLinks to the cells in a tableview.
Here is a snippet of my code. Appreciate the help. Thank you so much :)
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var url = String()
var yearsLinks = [String]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yearsLinks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
cell.textLabel?.text = yearsLinks[indexPath.row]
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let requests = URL(string: url){
let request = NSURLRequest(url: requests)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print(error as Any)
} else {
if let unwrappedData = data {
let wrappedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
...
// THESE ARE JUST CODE TO GRAB THE ARRAY THAT I WANT
// linkyears IS AN ARRAY OF VALUES DECLARED IN THE CLOSURE THAT I WANT TO SET TO THE yearsLinks VARIABLE DECLARED OUTSIDE.
self.yearsLinks = linkyears
...
print(self.yearsLinks) // THIS WORKS FINE AND RETURNS AN ARRAY OF VALUES THAT I WANTED.
}
}
}
}
// TRYING TO ACCESS THE ARRAY OF VALUES IN THE yearsLinks ARRAY RETURNS AN EMPTY STRING??
task.resume()
}
}
}