我的快速代码有问题。我正在尝试将数组 yearsLinks 设置为我的闭包内的一个值,并且当我仍在闭包中时我能够执行此操作并打印它但是当我尝试在闭包之外打印数组值时,它返回一个空数组. 为什么是这样?。
请帮忙,我想设置数组值,yearLinks 到表格视图中的单元格。
这是我的代码片段。感谢帮助。太感谢了 :)
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()
}
}
}