数组大小总是 returns 0 in Swift

Size of array always returns 0 in Swift

Swift 中的数组有问题。 如果我在 initialization 方法中有 print(self.days.count),我总能在数组 days 中得到正确数量的对象。但是,如果我在 viewDidLoad() 中使用 print(self.days.count),我总是得到 0。有什么办法可以修复它吗?感谢您的帮助。

import UIKit

class ViewController: UIViewController, UITableViewDelegate{
    //object array for weather
    var objectArray = [WeaObject]()
    var days = [List]()
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        initialization {
            print("succ")
            print(self.days.count)
        }
        tableView.delegate = self
        tableView.delegate = self
        print(days.count)
        //print(objectArray.count)
    }

    func initialization(completed:@escaping () -> ()){
        let jsonUrlString="http://api.openweathermap.org/data/2.5/forecast?zip=22003&appid=c632597b1892b4d415c64ca0e9fca1f1"
        guard let url = URL(string: jsonUrlString) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, err) in
            guard let data = data else { return }
            do {
                let downloadDays = try JSONDecoder().decode(TestingClass.self, from: data)
                self.days = downloadDays.list
                DispatchQueue.main.async {
                    completed()
                }
            } catch let jsonErr {
                print("Error serializing json:", jsonErr)
            }
        }.resume()
    }
}

您需要在 initialization 完成块内的 table 视图上调用 reloadData()

更新viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.delegate = self

    initialization {
        print("succ")
        print(self.days.count)
        tableView.reloadData()
    }

    // Do not print days.count here because days isn't updated yet
}

最好在主队列上更新数据模型:

func initialization(completed:@escaping () -> ()){
    let jsonUrlString="http://api.openweathermap.org/data/2.5/forecast?zip=22003&appid=c632597b1892b4d415c64ca0e9fca1f1"
    guard let url = URL(string: jsonUrlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, err) in
        guard let data = data else { return }
        do {
            let downloadDays = try JSONDecoder().decode(TestingClass.self, from: data)
            DispatchQueue.main.async {
                self.days = downloadDays.list
                completed()
            }
        } catch let jsonErr {
            print("Error serializing json:", jsonErr)
        }
    }.resume()
}

你也应该符合UITableViewDataSource:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSoure {